Share
Sign In

Why did Elixir choose a keyword list as functions' optional parameters?

The keyword list is one of the most unusual concepts a regular developer encounters during their Elixir journey. I, too, have struggled with this concept. As I gain more experience with Elixir, I notice that keyword lists appear in various places, particularly as optional parameters at the end of function arguments.
I asked myself, "Why?"
When utilizing JavaScript, I prefer employing a map because all parameters have names, and there is no need to specify the order when describing what I wish to obtain from a function.
I requested ChatGPT to search with Bing to determine if there was a design concept behind the keyword list. It provided this link: https://elixirforum.com/t/why-keyword-lists-for-opts-instead-of-maps/29654.
Along the thread, I saw that Jose Valim explained why they chose a keyword list instead of a map.
Elixir had an option to choose either keyword lists and maps for options. The reason why we chose keyword lists are because they preserve user ordering and they allow duplicate keys. We use both features in Elixir itself. For example, in try/catch/after, we warn if you put after before catch, as that would read weird. Using maps would not allow us to warn in those cases, as you always have alphabetical ordering. When you do import Keyword, only: [get: 2, get: 3], those are duplicate keys. Keyword.__info__(:functions) returns duplicate keys too.

In other words, there are scenarios where keyword lists can be useful and unifying opts under keyword lists is reasonable. Community projects, such as Ecto, leverages them too. Plus other benefits such as Erlang compat.
I notice a few points.
It connects to a historical background with Erlang.
It appears that they prioritized expressiveness over other virtues, such as maintaining order.
To make it easier for them to have more flexible syntax sugar, it gave them the freedom of adding additional language constructs.
It was essential for them to maintain order.
To cover some of the duplications.