Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens in this If-Else in Haskell?

I am having this 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 can't understand why.

Can somebody explain it to me STEP-By-STEP? Thanks for help!

like image 216
basti12354 Avatar asked Dec 05 '22 05:12

basti12354


1 Answers

Ok, so let's first make the function definition a bit more clear by using indentation

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

So f is called with arguments 3 and 5 at first. y being 5 (i.e. not 0), the then branch is executed, which calls f with arguments 4 and 4. Since y is still not equal to 0, we go into the then branch again and call f with arguments 5 and 3. This goes on until we finally call f with x = 8 and y = 0. We then go into the conditional's else branch, which just returns x, i.e. 8.

Here is one way the expression f 3 5 could be reduced:

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
like image 133
fjh Avatar answered Jan 10 '23 20:01

fjh