Is it possible to add a `when` clause to a pattern match?

Is it possible to do something like this?

%{x: x} when Integer.is_odd(x) = %{x: 3}

This particular syntax doesn’t work.

According to the docs, it doesn’t look like variable assignment pattern matching is supported.
https://hexdocs.pm/elixir/master/guards.html#where-guards-can-be-used

Throwing in an anon function always works.

%{x: x} = fn(x) when Integer.is_odd(x) -> %{x: x} end.(3)
3 Likes