views:

226

answers:

4

I don't know why the following haskell source code for calculating products recursively only using addition doesn't work.

mult a b = a + mult a (b-1)

I'm always getting a stack overflow error.

+4  A: 

What happens if b is 0?

Michiel Buddingh'
In short, how does it know when to stop?
Edward Kmett
+11  A: 

You'll have to specify a termination condition, otherwise the recursion will run infinitely.

mult a 0 = 0
mult a b = a + mult a (b-1)
Dario
+1  A: 

with any recursive function, there should be at least 2 cases.

a base case and a recursive case.

to make this more explicit, the use of the case (like the cases I mentioned above) statement is nice and easy to understand.

mult a b = case b of
    0 -> 0                -- the base case, multiply by 0 = 0
    _ -> a + mult a (b-1) -- recursive addition case (_ matches anything
                          -- but 0 is already covered)
barkmadley
To be exact, _ matches anything, but if b is 0 it's already matched so we'd never get to the _ case.
Chris Lutz
+2  A: 

You could always try a more original, haskell-ish solution =P

 mult a b = sum $ take b $ repeat a
codebliss
What about `mult a b = sum [ a | i <- [1..b] ]` or even better `mult = (*)`
Dario
Very nice Haskell example!
Absolute0
Dario the question asks how to do it with only addition..
Absolute0
Well the question asks about recursion too
Dario
I'm sorry Dario, is there better for you? =Pmult a b = iterate (+a) 0 !! b
codebliss
Or even haskell-ish in eta-reduced form, without formal parameters :) - mult = (sum.).(.repeat).take
Matajon
I'm sorry sir Matajon, but you are now BANNED from lambdabot.
codebliss
`take b $ repeat a == replicate b a`
Dario
And then we just passed the line of effortless readability, although I'd assume a more experienced Data.List Haskeller than myself would understand "mult = sum . flip replicate" effortlessly.
codebliss