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
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)
aina+1refers to theadefined on that same line, so the definition is infinitely recursive. But whichado you want it to refer to? The parameter offooor the one defined on line 1? Why do you have so many variables nameda? What is the code meant to do? Is it just an experiment on how scope works?ado you want to refer to which definition? Do you want it to be the same asfoo a b = (a + 1) + foo (a + 1) (b - 1)or something else?