如何在Clojure中向向量中添加字符串

3

我对Clojure和函数式编程都不熟悉。

我想要执行一组if/else语句,如果条件成立,我想在列表末尾添加一些字符串。

在JavaScript中,代码应该是这样的:

const a = 1;
const b = 2;
const c = 1;

const errors = [];

if (a !== b) {
  errors.push("A and B should not be different");
}

if (a == c) {
  errors.push("A and C should not be equal");
}

console.log(errors);

我该怎样用Clojure实现这个?

2个回答

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
谢谢Taylor,正是我所需要的。 - math3vz

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")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接