条件组合运算符
Conditional composition operator
我想知道 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))
我想知道 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))