从 Clojure 中的集合文字中加入字符串元素
Join string elements from set literal in Clojure
具有 Python 和 C# 背景的 Clojure 开发新手。我有类似的东西:
(def coll #{
:key1 ["string1"]
:key2 ["string2"]})
我需要定义一个新字符串来连接两个键向量的值。我试过了
(clojure.string/join (get coll :key1 :key2))
(concat (get coll :key1 :key2))
虽然这些提取了第一个键的字符串值,但我无法获得第二个。
从集合中获取和连接两个值的惯用 Clojure 方法是什么?我想要的输出是:
"string1string2"
如果你有一张地图,而不是一组(如评论中所建议的),那么
(def coll {
:key1 ["string1"]
:key2 ["string2"]}) ; {:key1 ["string1"], :key2 ["string2"]}
(->> coll
vals ; (["string1"] ["string2"])
(apply concat) ; ("string1" "string2")
(apply str)) ; "string1string2"
你有一张地图,我猜你不希望 [ ... ]
舍入值,所以你的 collection 应该是:
(def coll {
:key1 "string1"
:key2 "string2"})
在那种情况下,您的第一次尝试已经不远了:
(clojure.string/join (vals coll))
;"string1string2"
如果您确实需要向量,因为每个值中要输入更多数据
(def coll {
:key1 ["string1" :more]
:key2 ["string2" :stuff]})
...然后你要挑选出你想要的元素:
(->> coll
vals
(map first)
clojure.string/join)
;"string1string2"
具有 Python 和 C# 背景的 Clojure 开发新手。我有类似的东西:
(def coll #{
:key1 ["string1"]
:key2 ["string2"]})
我需要定义一个新字符串来连接两个键向量的值。我试过了
(clojure.string/join (get coll :key1 :key2))
(concat (get coll :key1 :key2))
虽然这些提取了第一个键的字符串值,但我无法获得第二个。
从集合中获取和连接两个值的惯用 Clojure 方法是什么?我想要的输出是:
"string1string2"
如果你有一张地图,而不是一组(如评论中所建议的),那么
(def coll {
:key1 ["string1"]
:key2 ["string2"]}) ; {:key1 ["string1"], :key2 ["string2"]}
(->> coll
vals ; (["string1"] ["string2"])
(apply concat) ; ("string1" "string2")
(apply str)) ; "string1string2"
你有一张地图,我猜你不希望 [ ... ]
舍入值,所以你的 collection 应该是:
(def coll {
:key1 "string1"
:key2 "string2"})
在那种情况下,您的第一次尝试已经不远了:
(clojure.string/join (vals coll))
;"string1string2"
如果您确实需要向量,因为每个值中要输入更多数据
(def coll {
:key1 ["string1" :more]
:key2 ["string2" :stuff]})
...然后你要挑选出你想要的元素:
(->> coll
vals
(map first)
clojure.string/join)
;"string1string2"