Reputation: 163
The problem:
You are given a function
plusOne x = x + 1
. Without using any other(+)
s, define a recursive functionaddition
such thataddition x y
addsx
andy
together.
(from wikibooks.org)
My code (it does not work -- endless loop):
plusOne x = x + 1
addition x y
| x > 0 = addition (plusOne y) (x-1)
| otherwise = y
Questions:
plusOne
function to the addition
recursive function?Upvotes: 0
Views: 1450
Reputation: 10447
using ==
and 0
addition = add 0 where
add a y x | a == y = x
| otherwise = add (plusOne a) y (plusOne x)
Upvotes: 0
Reputation: 530843
You are mixing up x
and y
in your recursive case
addition x y | y > 0 = addition (plusOne x) (y - 1) -- x + y == (x + 1) + (y - 1)
| otherwise = x -- x + 0 = x
Upvotes: 1