clojure的 - > (箭头)操作员和可选操作

时间:2013-07-06 22:49:50

标签: syntax clojure operators

我在几种情况下运行,我想对具有可选功能的对象进行一系列操作。 “ - >” 中适用于同一对象上的命令序列(例如(c(b(a x)))变为( - > x a b c)),除非某些操作是可选的。例如,假设我想这样做:

(c
  (if (> (a x) 2)
     (b (a x))
     (a x)
     )
  )

有没有办法以更清晰的方式使用像“ - >”这样的操作?

1 个答案:

答案 0 :(得分:10)

你可以使用Clojure 1.5中新引入的cond->

(cond-> x
  true        a
  (> (a x) 2) b
  true        c)

或者,更好,

(-> x
  a
  (cond-> (> (a x) 2) b)
  c)

意思是,“取x,将其穿过a,取结果并通过b (> (a x) 2)进行处理,或者保持不变,最后取走你的内容已经通过c“来解决这个问题。

换句话说,cond->就像->,除了代替通过它来表达表达式的单个表单,需要测试+表单对,如果test为false并且用于线程,则跳过表单如果测试是真的:

(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
相关问题