Why do many functions use keyword lists as params?

Hi. I’m new to elixir and I’ve noticed that functions often take in a keyword list as a last parameter to pass in an arbitrary number of params.

I think I understand the concept but I’m curious as to why people don’t use maps instead if the lookup is faster than it is for linked lists. I think…

I’m guessing that since generally we are talking about a small number of params it doesn’t matter much but I’m curious what’s the reasoning behind this choice.

Thanks!

1 Like

Welcome. Yes, the number of params are usually small. More importantly,

assign(socket, var1: val1, var2: val2)

Looks nicer than:

assign(socket, %{var1: val1, var2: val2})

It feels like named arguments from Smalltalk or ObjectiveC.

The simpler syntax only works when the keyword list is the last argument of the function call.

3 Likes

Keywords also allow for duplicate keys.

For example, Elixir’s import syntax:

import Foo, only: [bar: 2, bar: 3]

Another example is Ecto’s keyword syntax:

from q in query,
  where: q.id == ^id,
  where: q.active == true

Welcome to the forums!

10 Likes

If a function has many arguments it’s easier to use if you put most (or even all) of them in a keyword list. That allows you to:

  • Only supply the arguments you want to pass and leave the others to their defaults;
  • Not get confused about argument order as you pass the arguments by name and don’t rely on their position in the argument list.
6 Likes

Thanks. Clear! :pray:

1 Like

The reasons given so far basically mean that keyword args make a nice ergonomic API. As you note though, maps are actually easier to work with, especially when pattern matching, so a very common pattern in libraries is to accept a list in the public function, but the immediately convert it to a map and then pass that around internally.

3 Likes

Thanks! I’ll keep that pattern in mind as I look into libraries and write more elixir code. If you remember one library off the top of the head that uses this pattern I’d love to take a look :slight_smile:

When you say it is easier for you to deal with maps when doing pattern matching, is that because you can do partial matches in maps or do you have something else in mind?

A related topic - Why keyword lists for opts instead of maps?

2 Likes