Maps as data structures in Clojure are functions of their keys – a nifty use case

There’re many ways to replace one character set to another, and after a year or so with Clojure I’ve just realized there’s one truly functional (and possibly idiomatic) – use of map as a function of its keys to make it happen. With the map function, they make the conversion really pleasant.

So, instead of this (taken from John Lawrence Aspden‘s A Very Gentle Introduction to Information Theory : Setting the Scene):

(defn coin-decoder [sq] (map #(if (= % 0) :T :H) sq))

use a map – the data structure – and the map – the function – as follows:

(defn decoder [m s] (map #(m %) s))

With the decoder function you can change a stream with a given transformation rules in a map, e.g.

user=> (decoder {:yes 1 :no 0} '(:yes :yes :no :yes))
(1 1 0 1)

Don’t get confused with the double meaning of map – once it’s a data structure and the other is a function. Both are readily available in Clojure to serve your needs well. Have fun as much as I do.

More about maps as functions of their keys in the official documentation of Clojure – Maps (IPersistentMap).

It’s a small tribute for the other functions I could learn about upon reading the aforementioned article of John. The article (and the others about the information theory) read, the tribute paid, the deal’s over :-)

Be Sociable, Share!
This entry was posted in Languages.

4 Responses to Maps as data structures in Clojure are functions of their keys – a nifty use case

  1. Craig Andera says:

    Or, since maps are functions, just (map m s) :)

    • Jacek Laskowski says:

      Doh, why could *I* not have figured it out myself?! It struck me to death with its simplicity. Thanks so much.

  2. MC says:

    Or all in one:

    (#(map %1 %2) {:yes 1 :no 0} '(:yes :yes :no :yes))
    • Jacek Laskowski says:

      It doesn’t buy you much – I’d say it’s brilliant to know you can do it, but such a one-liners make the code harder to understand, esp. by newcomers to Clojure. It’s not reusable either.

Leave a Reply

%d bloggers like this: