条件合成运算符

什么是新的

我想知道clojure中是否存在一些内置的函数组合运算符,允许我重写如下内容:

(def first-or-identity #(if (sequential? %) (first %) (identity %)))

缩短:

(def first-or-identity (if-composition sequential? first identity)

-

用例将能够按照以下内容写点东西:

(def eventbus-pub
  (async/pub eventbus (if-composition sequential? first identity)))

谢谢!

缩图

您可以使用以下功能执行此操作:

(defn if-composition [tester truer falser]
  (fn [x]
    (if (tester x) (truer x) (falser x))))

例如,

(map
 (if-composition even? #(quot % 2) #(inc (* 3 %)))
 (range 10))
;(0 4 1 10 2 16 3 22 4 28)

值得在identity默认情况下设置最后一个参数

(defn if-composition
  ([tester truer] (if-composition tester truer identity))
  ([tester truer falser]
   ... ))

例如,

(map (if-composition odd? #(* 2 %)) (range 10))
;(0 2 2 6 4 10 6 14 8 18)

现在我们可以将您的示例写为

(def first-or-identity (if-composition sequential? first))

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章