开发者

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.


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)


What happens if b is 0?


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

 mult a b = sum $ take b $ repeat 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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜