为什么 "and" 和 "or" 在收到列表后提供这些结果?

Why "and" and "or" provide these results after receiving lists?

我将 Racket 和 Dr. Racket 用于教育目的。

定义变量"x"和"y"后如下:

(define x (list 1 2 3))
(define y (list 4 5 6))

我决定使用这些变量创建 3 个不同的列表。

第一个:

(append x y)

>> '(1 2 3 4 5 6)

第二个:

(cons x y)

>> '((1 2 3) 4 5 6)

第三名:

(list x y)

>> ((1 2 3) (4 5 6))

之后,我决定对三个列表使用布尔运算符 "and" 和 "or"。令我惊讶的是输出。为什么会这样?为什么 "or" 和 "and" 选择其中一个列表?这个决定背后的比率是多少?

(and (append x y) (cons x y) (list x y))

>> '((1 2 3) (4 5 6))

(or (append x y) (cons x y) (list x y))

>> '(1 2 3 4 5 6)

很简单:and returns last 表达式的值是 truthy#f 如果至少有一个表达式为假,而 or returns 第一个 表达式的值为真,或者 #f 如果全部为真假的。

记住:在 Scheme 中,唯一的 false 值是 #f,而其他任何值都被认为是 true,因此我们使用绰号 "truthy" - 来表示非 false 值。特别是,在您的代码中:

(and (append x y) (cons x y) (list x y))

Returns 最后一个真值表达式的值:(list x y),而这个:

(or (append x y) (cons x y) (list x y))

Returns 第一个真值表达式的值:(append x y).

andor也是控制流操作符

你可以想到 andor 特殊的控制流运算符。他们没有功能。函数 and 将对其参数求值,然后可能 return truefalse.

在这种情况下,andor 不是函数,在某些情况下,并不是每个参数都被评估:

  • or 当它看到 true
  • 时立即 returns
  • and 当它看到 false
  • 时立即 returns

return值

两者也是 return 一个 true 值,当有一个时:

  • orreturn第一个
  • and return 是最后一个 true 值,当所有参数都为 true

因为true不仅意味着单个布尔值,而且大多数其他对象也是true,你看它return 是您案例中的一个列表。只有 #f 不是 true.

其他条件控制流运算符

示例为:

  • 如果
  • 条件
  • 案例
  • 除非