Reputation: 51
I am trying to understand recursion in Haskell. I want to write a simple recursive function with the following properties: if x > 50
then rec(x) = x - 5
and rec(x) = rec(rec(x+10))
otherwise.
This is what I came up with:
rec x = if x > 50
then x-5
else rec (rec (x+10))
The not recursive part seems to work fine, but the recursion doesn't. Every number less than 50 just return 50. For example rec 60 = 55
rec 40 = 50
rec 25 = 50
Any suggestions on how to fix my code would be appreciated.
Upvotes: 1
Views: 127
Reputation: 12093
For x <= 50
, your function is equivalent to:
rec' x = if x `mod` 5 == 0
then 50
else 45 + x `mod` 5
This can be checked by running a simple test:
all (\ x -> rec x == rec' x) [0..50]
As a consequence, you need to feed an input which is not a multiple of 5 to get an answer distinct from 50.
Upvotes: 3