首页 > 解决方案 > 添加括号更改条件评估

问题描述

我开始学习 Scheme 并偶然发现了这个奇怪的东西:鉴于以下程序:

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

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

为什么是这样?

标签: schemelisp

解决方案


如果你写:

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使用两个参数评估变量来调用该过程,0并将1其评估为它们所代表的数字。如果您进行替换,它将变为:

(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 中很重要。基本上(one two three)在Scheme中是one(two, three)在JS中。只是在 somtheing 周围添加括号就是()在 JS 中的某些内容之后添加。


推荐阅读