【问题标题】:What does "%&" mean in Clojure?Clojure 中的“%&”是什么意思?
【发布时间】:2015-08-23 09:48:55
【问题描述】:

我使用递归解决了58th 4clojure 问题,但后来我查看了另一个人的解决方案,发现:

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

这比我的解决方案更优雅。但我不明白%& 是什么意思? (我确实理解% 的含义,但当它与& 结合时则不理解)。有人可以对此有所了解吗?

【问题讨论】:

    标签: clojure


    【解决方案1】:

    根据this source,它表示“其余参数”。

    正文中的参数由参数的存在决定 采用 %、%n 或 %& 形式的文字。 % 是 %1、%n 的同义词 指定第 n 个 arg(从 1 开始),%& 指定其余 arg。

    请注意,& 语法让人想起函数参数 (see here) 中的 & more 参数,但 &%anonymous function shorthand 中工作。

    一些用于比较匿名函数和它们的匿名函数简写等效的代码:

    ;; 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%& 语法给出了其余参数的列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多