Elixir with macro `<-` and `=`
So Elixir with macro accepts Matching clauses <-
and Bare expressions =
. Both match patterns and do not leak variables assigned inside these structures.
with {:ok, width} <- Map.fetch(%{width: 10}, :width),
do: {:ok, 2 * width}
#=> {:ok, 20}
with {:ok, width} = Map.fetch(%{width: 10}, :width),
do: {:ok, 2 * width}
#=> {:ok, 20}
So what is the difference between these?
When a match fails, matching clauses <-
returns failed result but bare expressions =
raises a MatchError
:
with {:ok, width} <- Map.fetch(%{height: 10}, :width),
do: {:ok, 2 * width}
#=> :error
with {:ok, width} = Map.fetch(%{height: 10}, :width),
do: {:ok, 2 * width}
#=> ** (MatchError) no match of right hand side value: :error
Another difference is that when
guard is only available for matching clause.
with {:ok, width} when is_number(width) <- Map.fetch(%{width: 10}, :width),
do: {:ok, 2 * width}
#=> {:ok, 20}
Tweet