在Haskell的If-Else中会发生什么?

bas*_*354 4 haskell if-statement function

我在haskell中有这个if-else子句.

let f x y = if y/=0 then f (x+1) (y-1) else x in f 3 5
Run Code Online (Sandbox Code Playgroud)

结果是8.我无法理解为什么.

有人可以逐步向我解释吗?感谢帮助!

fjh*_*fjh 16

好的,让我们首先使用缩进使函数定义更加清晰

let f x y =
     if y/=0
         then f (x+1) (y-1)
         else x
in f 3 5
Run Code Online (Sandbox Code Playgroud)

因此f被调用,参数35在第一.y被5(即不为0),则then分支被执行,这调用f与参数44.由于y仍然不等于0,我们进入then分支再次调用F带参数的53.这一直持续到我们最终用x = 8和调用f 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
Run Code Online (Sandbox Code Playgroud)