0
votes

I have a string "101,R:102,R:301,L:302,L:999", and I want to write a function, which processes the string and return a map like below:

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

Below is what I wrote, but I am stuck at the reduce function. Any help will be appreciated. Thanks.

(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

1 Answers

4
votes

You're actually almost there:

  1. Change parameter order of process so that return-hash comes first;

  2. Use (fnil conj []) in place of conj in the update-in calls;

  3. Use (reduce process {} id-side-array) in get-hash.