Jörg
Jörg

Reputation: 11

Calculating a product recursively only using addition

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.

Upvotes: 1

Views: 911

Answers (4)

codebliss
codebliss

Reputation: 426

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

 mult a b = sum $ take b $ repeat a

Upvotes: 2

barkmadley
barkmadley

Reputation: 5297

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)

Upvotes: 1

Dario
Dario

Reputation: 49208

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)

Upvotes: 11

Michiel Buddingh
Michiel Buddingh

Reputation: 5919

What happens if b is 0?

Upvotes: 4

Related Questions