【问题标题】:what is the idiomatic way to write this clojure snippet to concat collection with a string?将这个 clojure 片段编写为用字符串连接集合的惯用方法是什么?
【发布时间】:2013-10-05 19:13:17
【问题描述】:

最好用一个例子来解释我正在尝试什么。

给定一个集合 ["apple" "orange" "banana"] 和连接字符串 "," 函数应该产生 "apple,orange,banana"

这是写这个函数的惯用方式吗?

user=> (defn my-concat[x st]
   (str (first x) (apply str (map #(str st %) (rest x)))))

user=> (my-concat "abcd" "!")
"a!b!c!d"

【问题讨论】:

    标签: clojure concat idioms


    【解决方案1】:

    如果你想要一个序列,你可以使用interpose函数,如果你只想要字符串结果,你可以使用clojure.string/join

    【讨论】:

    • 我查看了 clojure.string/join 源代码。它正在使用 StringBuilder。和循环/重复。我想知道为什么作者选择了那个实现?这可能是由于性能原因吗? join 可以写成 (apply str (interpose st coll))。
    • 我对这两个函数都进行了计时。 clojure.string/join 总是快 50% 左右
    • Interpose 做更多的工作来维护你的集合和你的分隔符的惰性交错。连接针对单个结果字符串进行了优化。
    猜你喜欢
    • 2011-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 1970-01-01
    相关资源
    最近更新 更多