What happens in this If-Else in Haskell?

I have an if-else clause in haskell.

let f x y = if y/=0 then f (x+1) (y-1) else x in f 3 5

The result is 8. I do not understand why.

Can someone explain this to me STEP-By-STEP? Thanks for the help!

+4
source share
1 answer

So first make the function definition clearer using indentation

let f x y =
     if y/=0
         then f (x+1) (y-1)
         else x
in f 3 5

, f 3 5. y 5 (.. 0), then, f 4 4. y 0, then f 5 3. , f x = 8 y = 0. else, x, .. 8.

f 3 5:

f 3 5 -- y /= 0, so we go into the then branch
=> f (3 + 1) (5 - 1)
=> f 4 4 -- then branch again
=> f (4 + 1) (4 - 1)
=> f 5 3
=> f (5 + 1) (3 - 1)
=> f 6 2
=> f (6 + 1) (2 - 1)
=> f 7 1
=> f (7 + 1) (1 - 1)
=> f 8 0 -- this time we go into the else branch
=> 8
+16

All Articles