1

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.

2
  • Irrelevant to your problem, but I'd look into guards. They'd make your function much cleaner (subjectively). Commented Sep 5, 2015 at 16:06
  • 1
    I would also advocate for guards (rec x | x > 50 = x - 5) and then I would suggest you also explain what you expect the function to return, because to me it seems working correctly. Commented Sep 5, 2015 at 18:34

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.