通过折叠Scheme来获取列表的“和" [英] Taking the 'and' of a list by folding in Scheme

查看:121
本文介绍了通过折叠Scheme来获取列表的“和"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在《计算机程序的结构和解释》一书中 由H. Abelson和G. J. Sussman与J. Sussman, accumulationfold-right在2.2.3节中介绍如下:

In the book Structure and Interpretation of Computer Programs by H. Abelson and G. J. Sussman with J. Sussman, the accumulation or fold-right is introduced in Section 2.2.3 as follows:

(define (accumulate op initial sequence)
  (if (null? sequence)
      initial
      (op (car sequence)
          (accumulate op initial (cdr sequence)))))

我试图通过编写以下内容来使用它来获取布尔变量列表的and:

I tried to use this to take the and of a list of Boolean variables, by writing:

(accumulate and 
            true 
            (list true true false))

但是,这给了我DrRacket(带有#lang sicp)中的错误and: bad syntax, 而我不得不这样做:

However, this gave me the error and: bad syntax in DrRacket (with #lang sicp), and I had to do this instead:

(accumulate (lambda (x y) (and x y))
            true
            (list true true false))

为什么?我相信and是一种特殊形式, 但是我对Scheme的理解还不够. 也许我只是错过了一些明显的错误...

Why? I believe it has something to do with how and is a special form, but I don't understand Scheme enough to say. Perhaps I'm just missing some obvious mistake...

推荐答案

您回答了自己的问题:and是具有特殊评估规则的特殊形式(不是正常过程!),并且accumulate需要正常过程,因此您需要将其包装在过程中.

You answered your own question: and is a special form (not a normal procedure!) with special evaluation rules, and accumulate expects a normal procedure, so you need to wrap it inside a procedure.

要了解为什么and是一种特殊形式,请考虑以下示例,这些示例说明and需要特殊的评估规则(与过程不同),因为它会在发现错误值时短路:

To see why and is a special form, consider these examples that demonstrate that and requires special evaluation rules (unlike procedures), because it short-circuits whenever it finds a false value:

; division by zero never gets executed
(and #f (/ 1 0))
=> #f

; division by zero gets executed during procedure invocation
((lambda (x y) (and x y)) #f (/ 1 0))
=>  /: division by zero

这篇关于通过折叠Scheme来获取列表的“和"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆