Search⌘ K
AI Features

Using the with form

Explore how to use Elixir's with form to manage multiple pattern matches and control flow efficiently. Understand its use in error handling within pipelines and applications, reducing conditional complexity while maintaining clear error management.

Introduction to Elixir’s with

Elixir’s special form with allows us to combine multiple matching clauses. If all clauses match, the code executes and returns the do block result. If one clause doesn’t match, the code stops and returns the value of the non-matching clause. It’s useful to combine clauses that can result in unexpected values. Then we can handle the error at a convenient point, reducing the conditional code for each error. We use with when we have function pipelines that can result in an error.

Using with in shop checkout

We’ll use with in the dungeon crawl application, but first, let’s look at a simple example:

$ iex
iex> c("shop.ex")
iex> Shop.checkout()
Quantity?
two

'''Output ->
It's not a
...