方案中的程序清单

List of procedures in scheme

在方案中,我希望能够有一个过程列表,我可以通过地图在数字列表上使用这些过程。

比如我有程序

(define (overten? x) (> x 10))

为什么用 (foo '(1 2 11 12) '()) 调用时会起作用?

(define (foo lst proc)
    (map overten? lst)
)

但这给出了一个错误调用 (foo '(1 2 11 12) '(overten?)) ?

(define (foo lst proc)
    (map (car proc) lst)
)

错误是

The object overten? is not applicable.

因为'(overten?)是一个包含符号的列表。只有当您评估 overten? 时,您才能取回该过程。您需要编写 (list overten?) 以便评估 list 的参数(与 quote 不同)。

Why does Scheme have both list and quote?

'(overten?)不是一个带程序的目录。这是一个带有符号的列表,与在任何范围内绑定到该名称的过程无关

您需要思考的评价:

overten? 
; ==> {procedure overten? blabla} 
;     (a implementation dependent representation of a procedure object
'overten 
; ==> overten? 
;     (just a symbol with name "overten?", nothing to do with the procedure object above)
(list overten? 'overten?) 
; ==> ({procedure overten? blabla} overten)
      a list where the first element is a procedure and the second a symbol with name "overten?"


(define another-name-quoted 'overten?) 
; ==> undefined
; 'overten? evaluated to a symbol, them bound to another-name-quoted
(define another-name overten?)         
; ==> undefined
; overten? evaluated to a procedure, then bound to another-name

程序 overten? 不比 another-nameoverten?。 这是我们使用过程列表的示例。它是 compose 过程的实现:

(define (my-compose . procs)
  (let* ((rprocs (if (zero? (length procs))
                     (list values)
                     (reverse procs)))
         (proc-init (car rprocs))
         (proc-list (cdr rprocs)))
    (lambda args
      (foldl (lambda (proc acc)
               (proc acc))
             (apply proc-init args)
             proc-list))))

(define sum-square-sub1-sqrt
  (my-compose inexact->exact
              floor
              sqrt
              sub1
              (lambda (x) (* x x))
              +))

(sum-square-sub1-sqrt 1 2 3) ; 5