Clojure中的"%&"是什么意思?

14

我使用递归解决了第58个 4clojure问题,但是后来看了别人的解决方案,发现了这个:

(fn [& fs] (reduce (fn [f g] #(f (apply g %&))) fs))

那个解决方案比我的更优雅,但我不明白 %& 是什么意思?(我知道单独的 % 代表什么,但是和 & 结合起来又是什么意思呢?)有人可以为我解释一下吗?

1个回答

15

根据该来源,其意为“rest arguments”。

函数体中的参数由采用形式为%、%n或%&的参数字面量的存在来确定。%是%1的同义词,%n指定第n个arg(从1开始),而%&指定一个rest arg。

请注意,& 语法让人想起函数参数中的 & more 参数(参见此处),但 &%匿名函数速记 中也可以使用。

以下是一些代码,可用于比较匿名函数及其匿名函数速记等效形式:

;; a fixed number of arguments (three in this case)
(#(println %1 %2 %3) 1 2 3)
((fn [a b c] (println a b c)) 1 2 3)

;; the result will be :
;;=>1 2 3
;;=>nil

;; a variable number of arguments (three or more in this case) :
((fn [a b c & more] (println a b c more)) 1 2 3 4 5)
(#(println %1 %2 %3 %&) 1 2 3 4 5)

;; the result will be :
;;=>1 2 3 (4 5)
;;=>nil

请注意,& more%&语法会给出其余参数的列表。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接