【问题标题】:Join string elements from set literal in Clojure从 Clojure 中的集合文字连接字符串元素
【发布时间】:2015-05-22 15:08:36
【问题描述】:

具有 Python 和 C# 背景的新 Clojure 开发人员。我有类似的东西:

(def coll #{
  :key1 ["string1"]
  :key2 ["string2"]})

我需要定义一个新字符串来连接两个键向量的值。我试过了

(clojure.string/join (get coll :key1 :key2))
(concat (get coll :key1 :key2))

虽然这些提取了第一个键的字符串值,但我无法获得第二个。

从一个集合中获取和连接两个值的惯用 Clojure 方法是什么?我想要的输出是:

"string1string2"

【问题讨论】:

  • 您的收藏是一个集合,而不是地图,请删除 # 符号,因为当前 coll 中有 4 个项目,而不是 2 个地图条目
  • 你为什么使用集合而不是地图?如果您有地图,您可以使用((juxt :key1 :key2) col) 按顺序获取两个值。
  • 试试select-keys -> vals -> (apply str ...) HTH
  • 感谢马克和李。通过放下锐利然后使用 (juxt) 切换到地图得到了想要的结果。

标签: string clojure


【解决方案1】:

你有一张地图,我猜你不希望 [ ... ] 围绕这些值,所以你的收藏应该是:

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

【讨论】:

    【解决方案2】:

    如果你有一张地图,而不是一组(如 cmets 中建议的那样)

    (def coll {
      :key1 ["string1"]
      :key2 ["string2"]}) ; {:key1 ["string1"], :key2 ["string2"]}
    
    
    (->> coll
         vals ; (["string1"] ["string2"])
         (apply concat) ; ("string1" "string2")
         (apply str)) ; "string1string2"
    

    【讨论】:

    • 这是 ->> 宏的有用说明。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-07-08
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多