Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the benefits of using keywords as keys in maps in Clojure?

Tags:

clojure

I've noticed that in Clojure it's common to use keywords as keys in a map, while in other languages that do not have such concept it is common to use strings.

What are benefits of using keywords instead of strings or other types?

like image 437
Ivan Mushketyk Avatar asked Dec 13 '15 09:12

Ivan Mushketyk


1 Answers

  1. Keywords are a symbol type, semantically distinguished from strings and with a smaller range of representable values. They can be namespaced, there are checks for legal use of namespaces and such, and hence users can be more confident in EDN keyword keys meaning what they expect than in e.g. JSON with the equivalent string keys.
  2. Keywords are interned, so all instances of a keyword refer to identically the same object. This is useful for e.g. equality checks.
  3. Keywords are functions, acting like get with themselves as the key argument. This is convenient for cases like "I want the phone number of all these people" - (map :phone-no people) vs. (map #(get % "phone-no") people)

Keywords are also convenient with let and other destructuring tools:

(let[{:keys [foo bar]} {:foo 1 :bar 30}]
  (+ foo bar)) ;;=>31

but this does actually apply to string keys as well using the less common :strs destructuring.

like image 101
Magos Avatar answered Sep 23 '22 22:09

Magos