I've been wrestling with this small Clojure snippet for a while, but kept getting the feeling that there is a more idiomatic, simpler approach.
Desired behaviour; convert "1" -> true, "0" -> false. Else return the argument as is:
(= (mapper {:column 0} ["monkey" "stuff"]) "monkey")
(= (mapper {:column 0} ["1" "stuff"]) true)
(= (mapper {:column 0} ["0" "stuff"]) false)
This was my first attempt; a naive imperative approach:
(defn mapper
[attr-map row]
(let [x (row (:column attr-map))
y ({"1" true "0" false} x)]
(if (nil? y)
x
y)))
Second attempt:
(defn mapper
[attr-map row]
((comp #({"1" true "0" false} % %) row :column) attr-map))
Can anyone find a better solution?
let
andif
aren't imperative, for example. "Functional" is used in one narrow sense to refer to methods that are common in functional programming. I think you're asking for "functional style" ways of doing what you want--nothing wrong with that. But the opposite of that style isn't "imperative", to my mind. (let
can be viewed as an anonymous function call.) – Mars