简体   繁体   English

考虑 function fx = let fx = x+1 in f ( fx)

[英]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:我正在学习 Haskell 的语法考试,并希望得到一些帮助,说明为什么这等于 2:

" Consider the function: fx = let fx = x+1 in f (fx) What is the value of let x=0 in fx? " “考虑 function:fx = let fx = x+1 in f (fx) let x=0 in fx 的值是多少?”

The answer to this is 2.这个问题的答案是 2。

But "let fx = x+1" means that f (x+1).但是“让 fx = x+1”意味着 f (x+1)。 And then if we let x = 0 wouldn't that leave f(1)?然后如果我们让 x = 0 不会留下 f(1) 吗?

Thank you for reading感谢您阅读

There are two different functions being used.使用了两种不同的功能。 In the original function, there is no recursion;在原来的function中,没有递归; all references to f refer to the function defined by the let expression, not the function being defined.所有对f的引用指的是由let表达式定义的 function,而不是正在定义的 function。 There are also two different scopes both containing a variable named x .还有两个不同的范围都包含一个名为x的变量。 It's clearer if you rename the inner function and its argument:如果重命名内部 function 及其参数,会更清楚:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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