I want to write a function in clojure which would return a map give a string of the form "key1$value1,key2$value2". I came up with this.
(defn get-map
"Returns a map of key value pairs from a string formatted in the form 'key1$value1,key2$value2'"
[line]
(let [result {}]
(for [item (split line #",")]
(let [pair (split item #"\$")]
(assoc result (nth pair 0)
(if (= (.size pair) 2) (nth pair 1) ""))))))
Although it works the only problem with this code is that it returns the map inside a list.
=>(get-map "key1$value1,key2,value2")
({"key1" "value1"} {"key2" "value2"})
I tried to return the result as the last expression of the first let form but then the result is an empty map.
(defn get-map
"Returns a map of key value pairs from a string formatted in the form 'key1$value1,key2$value2'"
[line]
(let [result {}]
(for [item (split line #",")]
(let [pair (split item #"\$")]
(assoc result (nth pair 0)
(if (= (.size pair) 2) (nth pair 1) ""))))
result))
=>(get-map "key1$value1,key2,value2")
{}
Two questions -
- How should I modify the function to return just the map, without the list wrapper?
- Why did returning the result as the last expression of the first let form return an empty map?
Also if you have suggestions to write the same function in a better, more idiomatic clojure way that would be appreciated.