Why use tuples for keyword list?

Why use tuples for keyword list when,

list = [{:a, 1}, {:b, 2}]

list == [a: 1, b: 2]

What’s the use?

The second version is actually just a shorthand for convenience. Internally, it will be transformed into a list of tuples.


While @wmnnd explains what it is, it doesn’t explain why it is.

The point of keyword list is to provide simple configuration format for all functions. But why not use maps for that? you may ask. There are 2 main reasons:

  • Maps in Erlang are quite new type. It first occurred in OTP 17 and become quite usable in OTP 18, earlier there was no such type built in. That is the reason why in Elixir we have Dict, HashDict, and HashSet modules (legacy stuff from 1.0 times).
  • Due to the above Erlang functions are using something called property lists as a configuration for functions, and these are basically the lists in form [{atom(), term()} | atom()], so this is like superset of the keyword list. The nice thing is that plain atom() in the property list is the same as {atom(), true} which mean that given superset can be very easily matched one to the another. So it was natural to use such syntax sugar in Elixir as well.

A big difference between keyword lists and maps clicked when I read:

Specifically (bold and ## comments added by me),

Keyword lists are important because they have three special characteristics:

  • Keys must be atoms.
  • Keys are ordered, as specified by the developer.
  • Keys can be given more than once.

For example, the Ecto library makes use of these features to provide an elegant DSL for writing database queries:

query = from w in Weather,
      where: w.prcp > 0,              ## where #1
      where: w.temp < 20,             ## where #2
     select: w

These characteristics are what prompted keyword lists to be the default mechanism for passing options to functions in Elixir.