我是Clojure和函数编程方面的新手。
我想执行一组if / else,如果条件为true,我想在列表的末尾附加一些字符串。
在JavaScript中会是这样:
for (basis=i*26; basis<name.Length
&& name[basis] != ' '
&& name[basis] != '-'
&& name[basis] != '('
&& name[basis] != ')'
&& name[basis] != ';'
&& name[basis] != ','
&& name[basis] != '.'
&& name[basis] != '"';
basis--) ;
如何用Clojure完成此操作?
答案 0 :(得分:6)
cond->
适用于有条件地修改某些值并将这些操作组合在一起的情况:
(def a 1)
(def b 2)
(def c 1)
(cond-> []
(not= a b) (conj "A and B should not be different")
(= a c) (conj "A and C should not be equal"))
cond->
的第一个参数是要通过右侧形式穿线的值;这是空向量。如果没有满足任何LHS条件,它将返回该空向量。对于满足的每个条件,它将向量值穿入RHS形式,此处为conj
,用于向向量中添加内容。
查看->
和->>
宏以获取其他线程示例。
答案 1 :(得分:1)
cond->
很好,但是对我而言,我宁愿组成一个实用函数使它看起来更具声明性:
(defn validation-messages [& data]
(keep (fn [[check v]] (when (check) v)) data))
(validation-messages
[#(not= a b) "A and B should not be different"]
[#(= a c) "A and C should not be equal"])
;;=> ("A and B should not be different" "A and C should not be equal")