如何使用reduce来更新地图

时间:2014-03-22 14:36:22

标签: clojure

我有一个字符串" 101,R:102,R:301,L:302,L:999" ,我想写一个函数,它处理字符串并返回如下所示的地图:

{
  :left     [301 302],
  :right    [101 102],
  :unknown  [999]
}

以下是我写的内容,但我坚持使用reduce功能。任何帮助将不胜感激。感谢。

(defn process
  [data return-hash]
  (let [id-side (str/split data #",")
        id (first id-side)
        side (second id-side)]
    (cond
      (= "L" side) (update-in return-hash [:left] conj id)
      (= "R" side) (update-in return-hash [:right] conj id)
      :else (update-in return-hash [:unknown] conj id)
      )
    ))

(defn get-hash
  [data]
  (let [id-side-array (str/split data #":")]
    (reduce
      // a function calling process() method to update the map
      id-side-array)
    ))

(get-hash "101,R:102,R:301,L:302,L:999") 
=> 
{
  :left     [301 302],
  :right    [101 102],
  :unknown  [999]
} 

1 个答案:

答案 0 :(得分:4)

你实际上几乎就在那里:

  1. 更改process的参数顺序,以便return-hash成为第一位;

  2. (fnil conj [])来电中使用conj代替update-in;

  3. (reduce process {} id-side-array)中使用get-hash

相关问题