首先,我将使用斯皮尔杰框架进行测试。
(it "turns the string into a hash-map"
(should= {1 "1" 2 "2" 3 "3"}
(format-string "1=1 2=2 3=3")))那我的密码是:
(:use [clojure.string :only (split)])
(defn format-string [string]
(split string #"\s+"))现在,format-string函数返回["1=1" "2=2" "3=3"],测试失败。正如您在我的测试中所看到的,我希望它返回一个包含由=符号指示的键值对的散列映射。
我尝试过一些事情,我已经接近了,但我不太明白如何进行这种转变。
编辑
找出了一个解决方案,尽管键是字符串而不是整数。
我的代码:
(defn format-board [route]
(let [[first second third] (split route #"\s+")]
(merge
(apply hash-map (split-at-equals first))
(apply hash-map (split-at-equals second))
(apply hash-map (split-at-equals third))这将返回{"1" "1" "2" "2" "3" "3"}。
发布于 2013-01-31 21:03:09
您已经在空格处拆分,但是需要在=分隔符处再次拆分。您可以使用正则表达式进行解析。一旦你有了你的对,你可以assoc到一个哈希映射。在这里,我使用了reduce来实现转换。
user=> (reduce #(assoc % (read-string (nth %2 1)) (nth %2 2)) {}
#_> (re-seq #"([^=\s]+)=([^=\s]+)" "1=1 2=2 3=3") )
{3 "3", 2 "2", 1 "1"}注键顺序不适用于散列映射。
user=> (= {1 "1", 2 "2", 3 "3"} *1)
true发布于 2013-08-12 10:37:58
下面是使用clojure.core.reducers的潜在并行版本
(require '[clojure.core.reducers :as r])
(require '[clojure.string :as s])
(def string-of-pairs "1=1 2=2 3=3 4=4")
; reducing fn to convert seq of (key, value) to hash-map
(defn rf ([] {}) ([acc [k v]] (assoc acc k v)))
; for large colls, fold will parallelize execution
(r/fold merge rf (r/map #(s/split % #"=") (s/split string-of-pairs #"\s+")))要更好地理解减速器,请查看这段视频,里奇在其中解释减速器背后的动机,并演示一些用法。
https://stackoverflow.com/questions/14634669
复制相似问题