【问题标题】:Adding parenthesis changes evaluation of condition添加括号更改条件评估
【发布时间】:2020-05-11 12:52:36
【问题描述】:

我开始学习 Scheme 并偶然发现了这个奇怪的东西: 给定以下过程:

(define (test x y) (if (= x 0) 0 y ))

当我创建一个条件时,它会在我添加括号时“按预期”评估:(test 0 1) 给出 0。但是当我不添加括号(并且我使用相同的输入)时,它会评估为错误条件:test 0 1 给出 1。

这是为什么?

【问题讨论】:

  • 这是 Scheme 语法。您必须使用括号来进行函数调用。
  • 我明白了,但在 Scheme 中是什么导致它评估为假?为什么它不只是给出一个词法错误?
  • 它没有评估为假。您正在查看您输入的内容,即1
  • 你根本没有调用这个函数。
  • 没错。这是一个读取-评估-打印循环。它读取您的输入,对其进行评估并打印结果。数字只是对自己进行评估。

标签: scheme lisp


【解决方案1】:

如果你写:

test 0 1

这与:

(begin
  test ; evaluate variable test => #<procedure:something...> or similar value
  0    ; evaluate literal 0 => 0
  1)   ; evaluate literal 1 => 1
==> 1  ; because 1 is the last expression in the block it is the result of it. 

当您执行(test 0 1) 时,您正在调用您将通过使用两个参数评估变量test 获得的过程01,这两个参数被评估为它们所代表的数字。如果您进行替换,它将变为:

(if (= 0 0) ; if 0 is the same numeric value as 0
    0       ; then evaluate 0
    1)      ; else evaluate 1
==> 0

在 JavaScript 中也是如此:

const test = (x, y) => x === 0 ? 0 : y;
test;0;1    
==> 1        // result in node is 1 since it was the last expression

test(0, 1); // calling the fucntion behind the variable test with the arguments 0 and 1
==> 0

所以括号对事物很重要,因为它们在 JavaScript 中很重要。基本上,Scheme 中的 (one two three) 是 JS 中的 one(two, three)。只需在 somtheing 周围添加括号就是在 JS 中的某些内容之后添加 ()

【讨论】:

  • 谢谢,谢谢!我想要解释为什么,而不仅仅是如何,这就是我要寻找的。​​span>
猜你喜欢
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 2019-10-17
  • 1970-01-01
  • 2018-02-10
  • 2018-05-07
  • 1970-01-01
  • 2022-01-23
相关资源
最近更新 更多