mpelia
mpelia

Reputation: 43

Haskell code using a pre definite variable

Could anybody tell me why the following code in Haskell is not working?

a = 5
foo :: Int -> Int -> Int
foo a 0 = 0
foo a b = a + foo a (b - 1)
  where
    a = a + 1

Upvotes: 1

Views: 61

Answers (1)

sepp2k
sepp2k

Reputation: 370415

In Haskell a variable is in scope during its definition, so in a = a + 1, the a is referring to itself. If we rename the variables in your code, so that all variables have unique names, it will look like this:

a1 = 5
foo :: Int -> Int -> Int
foo _ 0 = 0
foo a2 b = a3 + foo a3 (b - 1)
  where
    a3 = a3 + 1

So the problem here is that a3 = a3 + 1 is infinitely recursive - a3 can't be equal to its own value plus one. Also a2 is never used.

You said that you wanted it to refer to the value of the parameter, so now that the variables have different names we can fix this easily enough:

foo :: Int -> Int -> Int
foo _ 0 = 0
foo a2 b = a3 + foo a3 (b - 1)
  where
    a3 = a2 + 1

Note that I've left out a1 this time since it's irrelevant to the foo function. We can also get rid of the where and just inline the a2 + 1 part (and rename a2 back to a since there will no longer be multiple ones):

foo :: Int -> Int -> Int
foo _ 0 = 0
foo a b = (a + 1) + foo (a + 1) (b - 1)

Upvotes: 4

Related Questions