josevalim
Discussion: Incorporating Erlang/OTP 21 map guards in Elixir
Hi everyone,
Erlang/OTP 21 comes with two new guards contributed by @michalmuskala: map_get/2 and is_map_key/2. Now we need to discuss how we would integrate those in Elixir. This proposal will be broken in three parts, each with their own discussion. Feel free to comment on any conclusion individually or as a group, but please let us know why.
NOTE: this is a focused thread, so we appreciate if everybody stayed on topic. Feel free to comment anything in regards to maps and guards but avoid off-topic or loosely related topics. For example, if you would like to know when other OTP 21 features will be added to Elixir, please use a separate thread.
The map_get/2 and is_map_key/2 guards
The first topic to consider is if we want to add the map_get/2 and is_map_key/2 guards to Kernel. Here are some things to consider.
First of all, in Elixir we don’t duplicate Kernel functionality in other modules. For example, since we have Kernel.map_size/1, there is no such thing as Map.size/1. However, given that we have Map.fetch!/2 (equivalent to map_get/2) and Map.has_key?/2 (equivalent to is_map_key/2), adding those two new guards means we would break those rules, as we simply can’t remove the Map functions.
Second of all, I am not particularly sure that map_get/2 and is_map_key/2 are beneficial in actual code, since they don’t add anything that you can’t do with a pattern matching. Let’s see the website example, without guards:
def serve_drinks(%User{age: age} = user) when age >= 21 do
...
end
Now written with guards:
def serve_drinks(%User{} = user) when map_get(user, :age) >= 21 do
...
end
Or if we assume we don’t need to check for the struct name:
def serve_drinks(user) when map_get(user, :age) >= 21 do
...
end
In both cases, I personally prefer the original example. It is clearer and promote better and more performant practices (pattern matching instead of field access).
In my opinion, the real advantage of map_get/2 and is_map_key/2 is that we can use them to build composable guards. For example, now we can finally implement guards such as is_struct/1:
defguard is_struct(struct)
when is_map(struct) and
:erlang.is_map_key(:__struct__, struct) and
is_atom(:erlang.map_get(:__struct__, struct))
Luckily, to implement those guards, we don’t need to add is_map_key/2 and map_get/2 to Elixir. We can just invoke them from the :erlang module.
Discussion #1: Should we add map_get/2 and is_map_key/2 to Kernel?
Expand defguard
If the main goal of map_get/2 and is_map_key/2 is to help in the construction of composable guards, then one possible route to take is to expand the defguard construct, introduced in Elixir v1.6, to also support patterns. Such that the following:
def serve_drinks(%User{age: age} = user) when age >= 21 do
...
end
Could be written as:
defguard is_drinking_age(%User{age: age}) when age >= 21
def serve_drinks(user) when is_drinking_age(user)
The guard above would internally be written as:
defguard is_drinking_age(user)
when is_map(user) and
:erlang.is_map_key(:__struct__, user) and
:erlang.map_get(:__struct__, user) == User and
:erlang.is_map_key(:age, user) and
:erlang.map_get(:age, user) >= 21
We can translate almost any pattern to guards. The only exception are binary matches, which won’t be supported.
Discussion #2: Should we allow patterns in defguard/1?
Support map.field in guards
Yet another approach to take is to support only map.field in guards. Again, if we take the original example:
def serve_drinks(%User{age: age} = user) when age >= 21 do
...
end
We could write it as:
def serve_drinks(%User{} = user) when user.age >= 21 do
...
end
Or even as:
def serve_drinks(user) when user.age >= 21 do
...
end
Where the latest is, IMO, by far the most readable.
However, this also has its own issues. First of all, as we said in the first section, pattern matching is typically more performant and clearer. Second of all, the foo.bar syntax in Elixir can mean either map.field OR module.function. This may be the source of confusion since invoking remote functions is not allowed in guards and those will make the guard to fail. For example, if somebody passes serve_drinks(User) to def serve_drinks(user) when user.age >= 21 do, you will get a FunctionClauseError, as only passing maps would be supported. However, I personally don’t think this would be a large issue in practice, as guards have always been limitted, remote calls are never supported in guards and dynamic remote calls are rare anyway, especially zero-arity ones.
Discussion #3: Should we allow map.field in guards?
Most Liked
michalmuskala
Discussion #1: Should we add map_get/2 and is_map_key/2 to Kernel?
Yes, we should. There are things that can’t be expressed with the other proposals (or any other way in a guard for that matter), most notably:
def check_key(map, key) when is_list(map_get(map, key)), do: ...
It’s effectively implementing the def foo(key, %{key => value}) ... that is such a frequent request - now we’d have a way to do this.
However, I’m not a huge fan of the map_get name (pretty ironic considering it’s me who contributed it to Erlang). It feels very “imperative” while I find pattern matching and guards to be mostly about declarative code.
For example, for tuples, we use elem, not get_elem and for lists hd not get_hd (though head would probably be better). Because of that, I think we should explore adding this function under some different name. Some proposals: field, map_field, map_value, key_value, …
Discussion #2: Should we allow patterns in defguard/1?
Yes, I think we should. I like this idea a lot.
The only problem is that we might hit some performance issues with complex patterns when the value is used multiple times. Since we can’t bind inside guards, we’d have to generate the “access” code at each place the value is used. It becomes especially problematic when coupled with the in operator. It might lead to gigantic code explosion. I don’t think compiler would be smart enough to eliminate all those common sub-expressions (a long-term solution to this would be compiling to core erlang that allows binding in guards, that’s another set of issues, though).
With all of that said, I don’t think this should prevent us from exploring the implementation of this feature.
Discussion #3: Should we allow map.field in guards?
No. This feature would break the consistency of the language and make some construct mean different things inside and outside guards.
It’s true, today there’s difference in how code fails inside and outside guards (e.g. hd([]) might fail with an exception or just fail the current guard clause). When the expression fails or succeeds is always the same, though - this would break it and break it completely silently.
As a counter example, I could easily imagine somebody trying to write code like that:
def update_or_rollback(repo, changeset) do
case repo.update(changeset) do
{:error, reason} when repo.in_transaction?() -> repo.rollback(reason)
other -> other
end
end
Which would just silently fail. And it’s not a completely artificial example - in one of the projects I have a very similar function:
def update_or_rollback(repo, changeset) do
case repo.update(changeset) do
{:error, reason} = error ->
if repo.in_transaction?(), do: repo.rollback(reason), else: error
other -> other
end
end
gregvaughn
Discussion #1: Should we add map_get/2 and is_map_key/2 to Kernel?
no
Discussion #2: Should we allow patterns in defguard/1?
yes
Discussion #3: Should we allow map.field in guards?
no
The reason behind it is basically the same for each. We should encourage pattern matching. Having more ways of doing the same things will lead to more confusion.
josevalim
Related to the guards discussion, Elixir master use the new documentation metadata to annotate when we have guards. We are leveraging this information to show Guards in their own section in the docs sidebar: https://hexdocs.pm/elixir/master/Kernel.html
Popular in Proposals
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









