i've been learning clojure few weeks now. know basics of data structures , functions. (i'm reading clojure programming book).
i'm stuck following. i'm writing function lower case keys of supplied map.
(defn lower-case-map [m] (def lm {}) (doseq [k (keys m)] (assoc lm (str/lower-case k) (m k)))) this want, how return map? def correct?
i know works
(defn lower-case-map [m] (assoc {} :a 1)) but doseq above seems creating problem.
within function body should define local variables let, yet code looks alot try bend imperative mindset (def tempvar = new map; foreach k,v in m tempvar[k.tolower] = v; return tempvar). note, docs of doseq explicitly state, returns nil.
the functional approach map or reduce on input returning result directly. e.g. simple approach map (iterating sequence of elements, destructure key/value tuple, emit modified tuple, turn them map):
user=> (into {} (map (fn [[k v]] [(.tolowercase k) v]) {"a" 1 "b" 2})) {"a" 1, "b" 2} for use-case (modify keys in map) nice core function: reduce-kv:
user=> (doc reduce-kv) ------------------------- clojure.core/reduce-kv ([f init coll]) reduces associative collection. f should function of 3 arguments. returns result of applying f init, first key , first value in coll, applying f result , 2nd key , value, etc. if coll contains no entries, returns init , f not called. note reduce-kv supported on vectors, keys ordinals. user=> (reduce-kv (fn [m k v] (assoc m (.tolowercase k) v)) {} {"a" 1 "b" 2}) {"a" 1, "b" 2}
Comments
Post a Comment