首页 > 解决方案 > 如何在 Clojure 中将字符串附加到向量

问题描述

我是 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 做到这一点?

标签: clojure

解决方案


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这里用于向向量添加内容。

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


推荐阅读