Clojure分区字符串列表,累加结果
我很抱歉标题不够精确,但这可能说明我缺乏clojure的经验 我正在尝试获取一个大的字符串列表,并将该列表转换为另一个字符串列表,同时进行连接,直到累加器小于某个长度 例如,如果我有Clojure分区字符串列表,累加结果,clojure,Clojure,我很抱歉标题不够精确,但这可能说明我缺乏clojure的经验 我正在尝试获取一个大的字符串列表,并将该列表转换为另一个字符串列表,同时进行连接,直到累加器小于某个长度 例如,如果我有 [ "a" "bc" "def" "ghij" ] 我的最大字符串长度是4,我会沿着列表走下去,累加concat,直到累加len>4,然后从头开始累加。我的结果如下: [ "abc" "def" "ghij" ] 我似乎想不出正确的咒语来划分,这让我有点疯狂。我一直试图使我的累加器成为一个atom(但似乎不知道
[ "a" "bc" "def" "ghij" ]
我的最大字符串长度是4,我会沿着列表走下去,累加concat,直到累加len>4,然后从头开始累加。我的结果如下:
[ "abc" "def" "ghij" ]
我似乎想不出正确的咒语来划分,这让我有点疯狂。我一直试图使我的累加器成为一个atom
(但似乎不知道在哪里重置!
),但除此之外,我不知道在哪里/如何跟踪我累积的字符串
提前感谢所有怜悯我的人。以下是我将如何做到这一点:
(ns tst.demo.core
(:use demo.core tupelo.core tupelo.test))
(def bound 4)
(defn catter [strings-in]
(loop [merged-strs []
curr-merge (first strings-in)
remaining-strs (rest strings-in)]
;(newline) (spyx [merged-strs curr-merge remaining-strs])
(if (empty? remaining-strs)
(conj merged-strs curr-merge)
(let ; try using 'let-spy' instead
[new-str (first remaining-strs)
new-merge (str curr-merge new-str)]
(if (< (count new-merge) bound)
(recur merged-strs new-merge (rest remaining-strs))
(recur (conj merged-strs curr-merge) new-str (rest remaining-strs)))))))
(dotest
(is= ["abc" "def" "ghij"] (catter ["a" "bc" "def" "ghij"]) )
(is= ["abc" "def" "ghij"] (catter ["a" "b" "c" "def" "ghij"]) )
(is= ["abc" "def" "ghij"] (catter ["a" "b" "c" "d" "ef" "ghij"]) )
(is= ["abc" "def" "ghij"] (catter ["a" "bc" "d" "ef" "ghij"]) )
(is= ["abc" "def" "ghij"] (catter ["a" "bc" "d" "e" "f" "ghij"]) )
(is= ["abc" "def" "gh" "ij"] (catter ["abc" "d" "e" "f" "gh" "ij"]) )
(is= ["abc" "def" "ghi" "j"] (catter ["abc" "d" "e" "f" "ghi" "j"]) )
(is= ["abcdef" "ghi" "j"] (catter ["abcdef" "ghi" "j"]) )
(is= ["abcdef" "ghi" "j"] (catter ["abcdef" "g" "h" "i" "j"]) )
)
这很接近。我不知道为什么在最后一个字符串的末尾有j
(sequence
(comp
(mapcat seq)
(partition-all 3)
(map clojure.string/join))
["a" "bc" "def" "ghij"]) => ("abc" "def" "ghi" "j")
以下是我对此的看法:
(defn折叠[maxlen xs]
(让[concats(take while#)(<(count%)maxlen)(str xs))]
(cons(最后一个concats)(drop(count concats)xs)))
(折叠4[“a”“bc”“def”“ghij]”)
;; => (“abc”“def”“ghij”)
该方法是正确的,但它只在子序列位于输入的开头时起作用。将因以下原因而失败:(折叠4[“a”“bc”“def”“ghij”“z”“xc”“vbn])
=>(“abc”“def”“ghij”“z”“xc”“vbn”)
,或(折叠4[“asdf”“a”“bc”“def”“ghij])
(无“asdf”“a”“bc def”“ghij”)
。。感谢所有的回复者——我将把所有的建议作为一种学习经验,并在我理解的时候接受答案。再次感谢!你的确切要求有些不确定。你能看一下我的答案中包含的单元测试,并验证这就是你所寻求的行为吗?谢谢
(sequence
(comp
(mapcat seq)
(partition-all 3)
(map clojure.string/join))
["a" "bc" "def" "ghij"]) => ("abc" "def" "ghi" "j")
(defn catsize [limit strs]
(reduce (fn [res s]
(let [base (peek res)]
(if (> (+ (.length ^String base) (.length ^String s)) limit)
(conj res s)
(conj (pop res) (str base s)))))
(if (seq strs) [(first strs)] [])
(rest strs)))