0

I am stuck with the variable not in scope: m error. This is supposed to be a code to sum n numbers in a tail recursion way.

zum :: Integer-> Integer 
zum n = add_sum m n where
add_sum :: Integer-> Integer-> Integer
add_sum m n
    | n == 0    = m
    | otherwise = add_sum (m+n) (n-1)
Sourav Ghosh
  • 1,964
  • 4
  • 33
  • 43
Pelin
  • 127
  • 6
  • 2
    In your line `zum n = add_sum m n` where do you define `m`? – Willem Van Onsem May 02 '17 at 17:48
  • ahh, yes! thanks! It is that line. I found the problem! It should be: zum n = add_sum 0 n where – Pelin May 02 '17 at 17:58
  • 2
    good. you can add an answer (it is allowed) and accept it, to mark the issue resolved. – Will Ness May 02 '17 at 18:00
  • done! thanks again. – Pelin May 02 '17 at 18:11
  • I'm not sure that this is tail-recursive, by the way. The compiler might be smart enough to recognize it, but using guards is syntactic sugar for a large if/else expression. Someone can correct me if I'm wrong, but I think your function will expand to `if n == 0 then m else if (n - 1) == 0 then m+1 else if ...`. More info [here](http://stackoverflow.com/questions/4092864/tail-recursion-in-haskell). You want to define `add_sum` in a way that it matches against the arguments rather than using guards. – Mokosha May 02 '17 at 18:13
  • @Mokosha hmm, I hesitate now too. I will read a bit more about it. – Pelin May 02 '17 at 20:27

2 Answers2

1

In the second line of your code

zum n = add_sum m n where

'm' is not defined. Perhaps it was intended that instead of an 'm', there needs to be 0 there.

0

perhaps cleaner this way?

sum n = go 0 n
     where go m 0 = m
           go m n = go (m+n) (n-1)


> sum 4
10
karakfa
  • 66,216
  • 7
  • 41
  • 56