However this style breaks down as soon as you have to do something more complicated than thread a single value, or have to do something more complicated than pass failures through.
def get_cute_cat(image_id) do
with {:ok, cropped} <- find_cat(image_id),
{:ok, with_tie} <- add_bowtie(cropped),
{:ok, with_sparkles} <- make_eyes_sparkle(with_tie)
do
with_sparkles
|> make_smaller()
|> add_rainbow()
end
end
If any of the values on the rhs of a `<-` cannot be pattern matched, it returns up the returned value. This value can be pattern matched easily inside an `else` clause underneath the main block. The use of the `:ok,` vs `:error,` tuple convention allows multiple values to be destructured and passed around if needed (rather than an optional type).If you find the code getting unwieldily, as runeks said you can break it down into simpler constructs.