1

The following code gives me a stack overflow error in some cases (ex hosum (\x->x `mod` 3) 1000 ) and I don't understand why. Could anyone explain this to me? (I am new to Haskell and I'd appreciate any help :) )

 hosum :: (Int -> Int) ->  (Int -> Int)
    hosum f  = (\x -> hs f x (- x))
            where hs :: (Int -> Int) -> Int -> Int -> Int
                  hs f 0 0 = f 0
                  hs f n m
                          | m <= n 
                          = f m + hs f n (m+1)
                          | n <= m 
                          = f n + hs f (n+1) m
                          | otherwise
                          = 0

1 Answer 1

3

The stack overflow is likely caused by the infinite recursion. Your guards are m <= n and n <= m; for every n and m, one of those is always true. Your otherwise is never reached, the recursion never terminates. You probably meant your guards to be m < n and n < m.

Your hs should therefore be

hs f 0 0 = f 0
hs f n m | m < n     = f m + hs f n (m + 1)
         | m > n     = f n + hs f (n + 1) m
         | otherwise = 0

Because of that last guard, you could even remove the pattern hs f 0 0; the otherwise catches that one.

Sign up to request clarification or add additional context in comments.

2 Comments

oh ok, I understand. Thank you so much :)
I second removing the hs f 0 0 case. It looks funny to see that as a base case, when n,m are increasing (by 1) in each recursive call.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.