red*_*h64 6 syntax clojure operators
我已经在几种情况下运行,我想对一个带有可选功能的对象进行一系列操作." - >"适用于同一对象上的命令序列(例如(c(b(ax)))变为( - > xabc)),除非某些操作是可选的.例如,假设我想这样做:
(c
(if (> (a x) 2)
(b (a x))
(a x)
)
)
Run Code Online (Sandbox Code Playgroud)
有没有办法以更清晰的方式使用" - >"这样的操作?
Mic*_*zyk 10
你可以cond->在Clojure 1.5中新引入它:
(cond-> x
true a
(> (a x) 2) b
true c)
Run Code Online (Sandbox Code Playgroud)
或更好,
(-> x
a
(cond-> (> (a x) 2) b)
c)
Run Code Online (Sandbox Code Playgroud)
意思是"接受x,穿过它a,获取结果并将其穿过,b如果(> (a x) 2)或者保持不变,最后采取你已经得到的东西并通过它c".
换句话说,cond->就像是->,除了代替单个表单通过它来表示你的表达式需要test + form对,如果test为false,则跳过表单,如果test是真的则用于线程:
(cond-> x
test-1 form-1
test-2 form-2)
;; if test-1 is truthy and test-2 is falsey, output is as if from
(-> x test-1)
;; if it's the other way around, output is as if from
(-> x test-2)
;; if both tests are truthy:
(-> x test-1 test-2)
;; if both tests are falsey:
x
Run Code Online (Sandbox Code Playgroud)