博士。 Racket 用户。
这里有两种表达方式:
((lambda(x)(+ x 1))3)
((lambda(x)(+ x 1)2)3)
第一个是一个 lambda 表达式,它接受一个输入并将其增加 1。因此它将 3 作为其操作数并使 (lambda(3)(+ 3 1) 等于 4。
第二个对我来说非常模棱两可,因为它的评估结果为 2,我无法理解它的评估顺序。我知道它必须与改变顺序的括号有关,但我不明白如何。显然,它甚至不将“1”和“x”相加,只是出于某种原因产生 2 作为输出。我错过了对评估的一些基本了解。提前致谢!
最佳答案
如 Racket docs 中所述:
A function definition can include multiple expressions for the function’s body. In that case, only the value of the last expression is returned when the function is called. The other expressions are evaluated only for some side-effect, such as printing.
例如:
(define (f x)
(+ 1 1) ;; evaluates to 2, but not returned
(= 3 4) ;; evaluates to false, but not returned
0 ;; evaluates to 0, but not returned
1000 ;; evaluates to 1000, but not returned
pi ;; evaluates to pi, but not returned
"I am a string") ;; last expression; evaluates and returns "I am a string"
和
(f 10)
=> "I am a string"
(f 'okay)
=> "I am a string"
(f pi)
=> "I am a string"
在你的最后一个 lambda 中也发生了同样的事情,其中:
((lambda (x) (+ x 1) 2) 3)
=> ((lambda () (+ 3 1) 2))
=> ((lambda () 4 2)) ;; last expression is 2, so output 2
=> 2
关于lambda - Scheme 中 lambda 表达式的求值顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47164095/