"with" syntax: Difference between <- and =

The Elixir docs show using <- when using the “with” special form, e.g.

with {:ok var} <- do_something(),
     {:ok, var2} <- do_something_else()
do
  whatever(var, var2)
end

However! Programming Elixir 1.6’s examples show the arrows replaced with a plain old pattern match with =, e.g.

with {:ok, var} = do_something(),
     {:ok, var2} = do_something_else()
do
  whatever(var, var2)
end

One of the examples even mixes using = and <- in the items inside the with statement.

What’s the difference? Is there something subtle I’m missing, or is the book wrong? Just about every other example I’ve seen online and the official docs show <-

2 Likes

= does raise if there’s no match (so it’s not really useful in with) while <- just falls through to the else part of with if there’s no match. The same thing is true for for.

for {key, value} <- [:a, :b, :c, d: 5, e: 5], do: {key, value}
# [d: 5, e: 5]

Any non match won’t raise, but go to the next iteration.

8 Likes

Aha! Thanks!

Looking at the Pragprog book, there is indeed a paragraph that explains the difference, and I must have totally glossed over it.

2 Likes

Thanks for asking the question (and the great answers). I’ve read through the book too and completely missed this; I just assumed you had to use <- exclusively.

Knowing the difference will probably come in handy in the future!