应用功能

如果你有一个列表,并且你想使用该列表的元素作为函数的参数,你想要的是 apply

> (apply string-append (list "hello" " " "and hi" " " "are both words"))
"hello and hi are both words"
> (apply + (list 1 2 3 4))
10
> (apply append (list (list "a" "b" "c") (list 1 2 3) (list "do" "re" "mi")))
(list "a" "b" "c" 1 2 3 "do" "re" "me")

apply 有两个参数。第一个参数是要应用的函数,第二个参数是包含参数的列表。

一个 apply 的调用就像

(apply + (list 1 2 3 4))

相当于

(+ 1 2 3 4)

apply 的主要优点是它适用于任意计算列表,包括来自函数参数的附加列表和列表。

> (apply + (append (list 1 2 3 4) (list 2 3 4)))
19
> (define (sum lst)
    (apply + lst))
> (sum (list 1 2 3 4))
10
> (sum (append (list 1 2 3 4) (list 2 3 4)))
19

有关更多信息和示例,请参阅 球拍指南”中apply 功能