lambda - Scheme 中 lambda 表达式的求值顺序

标签 lambda scheme racket brackets

博士。 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/

相关文章:

python - 当我使用 lambda 表达式或赋值时,列表元素消失了

scheme - 模拟 scheme 在 common lisp 中定义

properties - 如何格式化可执行文件的属性详细信息

scheme - 在 Scheme 中检查对象是否为 "listdiff"

c# - 如何在 Distinct 中使用 lambda 表达式

c# - 表达式树和调用委托(delegate)

iphone - 有类似 Haskell/ML 的 C 编译器吗?

struct - 如何在 Racket 中为编译时提供结构元数据的同时覆盖结构构造函数?

if-statement - Racket 中的 If 语句

c# - 将 Lambda LINQ 语句作为 Func<> 传递时出现问题