【问题标题】:Function composition in Clojure?Clojure中的函数组合?
【发布时间】:2010-05-12 19:33:30
【问题描述】:

Clojure 可以实现像 Haskell 的 g . f 这样的 (g ∘ f) 构造吗?我目前正在使用(fn [n] (not (zero? n))) 之类的变通方法,但效果不太好:)

【问题讨论】:

    标签: clojure


    【解决方案1】:

    clojure.core 中有一个名为 comp 的函数可以执行此操作。例如

    ((comp not zero?) 5)
    ; => true
    

    您可能还想考虑使用-> / ->>,例如

    (-> 5 zero? not)
    ; => true
    

    【讨论】:

    • 确保在 Haskell 中进行“currying”时使用partial。所以对于 map/reduce,你需要做 (let [reducer (comp (partial reduce +) (partial map get-value))] (reducer my-things))
    • 也可以将comp not替换为complement((complement zero?) 5)
    【解决方案2】:

    您可以使用 Clojure 的匿名函数读取器宏快捷方式,以更少的击键次数重写您的版本。

    user=> (#(not (zero? %)) 1)
    true
    

    对于组合not和其他函数的具体情况,可以使用complement

    user=> ((complement zero?) 1)
    true
    

    notwhenif 结合使用很常见,if-notwhen-not 是核心功能。

    user=> (if-not (zero? 1) :nonzero :zero)
    :nonzero
    

    【讨论】:

    • reader-macro 快捷方式似乎非常有用,因为代码简洁易读。我也不知道“if-not”和“when-not”,谢谢!
    • *核心宏。 if-notwhen-not 是宏,因此没有运行时成本。
    【解决方案3】:

    另一种方式是(reduce #(%2 %1) n [zero? not]),但我更喜欢 Michal 已经提到的 (comp not zero?)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-04
      • 2015-12-15
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2020-05-02
      • 2016-02-01
      相关资源
      最近更新 更多