clojure - 如何在 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 做到这一点?
解决方案
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
这里用于向向量添加内容。
查看->
和->>
宏以获取其他线程示例。
推荐阅读
- python - AttributeError:'CallbackContext'('Update')对象没有属性'message',python
- javascript - Rollup + React 17 与新的 JSX 转换 - “React 未定义”
- go - 使用通道作为队列的死锁
- powerbi - 我需要在 Power BI 中转换 excel countifs 公式
- python - Pandas numpy 处理 Nan
- arrays - 如何查看字符串是否在字符串数组中C
- next.js - Next JS Slug Page 赢得了 vercel 部署的工作
- python - 使用 pandas 数据框创建列表理解
- c++ - C++:在不使用锁的情况下比较 2 个整数变量时如何避免竞争条件
- asp.net - 以角度查询字符串加密并从asp.net解密