简体   繁体   中英

Considering a function f x = let f x = x+1 in f ( f x)

I'm studying for a syntax exam in Haskell and would love to receive some help of why this equals to 2:

" Consider the function: fx = let fx = x+1 in f (fx) What is the value of let x=0 in fx? "

The answer to this is 2.

But "let fx = x+1" means that f (x+1). And then if we let x = 0 wouldn't that leave f(1)?

Thank you for reading

There are two different functions being used. In the original function, there is no recursion; all references to f refer to the function defined by the let expression, not the function being defined. There are also two different scopes both containing a variable named x . It's clearer if you rename the inner function and its argument:

f x = let f' x' = x' + 1 in f' (f' x)

Now the other expression is easier to evaluate using equational reasoning:

let x = 0 in f x == f 0
                 == let f' x' = x' + 1 in f' (f' 0)
                 == (f' 0) + 1
                 == (0 + 1) + 1
                 == 1 + 1
                 == 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM