如何在Clojure中将字符串附加到向量

mat*_*3vz 3 clojure

我是Clojure和函数编程方面的新手。

我想执行一组if / else,如果条件为true,我想在列表的处追加一些字符串。

在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);

Run Code Online (Sandbox Code Playgroud)

我如何用Clojure完成此操作?

Tay*_*ood 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"))
Run Code Online (Sandbox Code Playgroud)

第一个参数cond->是要通过右侧形式穿线的值;这是空向量。如果没有满足任何LHS条件,它将返回该空向量。对于满足的每个条件,它将向量值穿入RHS表单,conj此处用于向向量添加内容。

请查看->->>宏,以获取其他线程示例。