Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Clojure 条件复合算子_Clojure - Fatal编程技术网

Clojure 条件复合算子

Clojure 条件复合算子,clojure,Clojure,我想知道clojure中是否存在内置的函数组合运算符,允许我重写如下内容: (def first或identity#(if(sequential?%)(first%)(identity%)) 进入一个较短的阶段: (def first或identity(如果组合顺序?第一个identity) -- 用例将能够沿着这些行写一些东西: (def eventbus-pub (async/pub eventbus (if-composition sequential? first identity)

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

(def first或identity#(if(sequential?%)(first%)(identity%))

进入一个较短的阶段:

(def first或identity(如果组合顺序?第一个identity)

--

用例将能够沿着这些行写一些东西:

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

Thanx!

您可以通过以下功能完成此操作:

(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)
(map (if-composition odd? #(* 2 %)) (range 10))
;(0 2 2 6 4 10 6 14 8 18)
默认情况下,创建最后一个参数
identity
是值得的:

(defn if-composition
  ([tester truer] (if-composition tester truer identity))
  ([tester truer falser]
   ... ))
比如说,

(map
 (if-composition even? #(quot % 2) #(inc (* 3 %)))
 (range 10))
;(0 4 1 10 2 16 3 22 4 28)
(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))

您还可以使用
apply
扩展到任意算术:
(fn[&args]if(apply tester args)(apply truer args)(apply falser args))
。除非FN都具有相同的算术性,否则显然不会很好地工作。@user1571406是的。我想那些没有看到的人会被它弄糊涂。如果你将任何函数所需的所有参数都放入混合中,你总是可以将它们包装为忽略不必要的参数的函数。这与非常感谢你的回答。它的简单性非常好。我特别喜欢默认身份的想法。