From 8b616c1acf479b5f0e0daf046bf37fac94823021 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sun, 10 Mar 2019 12:21:37 -0500 Subject: [PATCH] Add Match On A Map In A With Construct as an elixir til --- README.md | 3 ++- elixir/match-on-a-map-in-a-with-construct.md | 25 ++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 elixir/match-on-a-map-in-a-with-construct.md diff --git a/README.md b/README.md index d580062..c22059c 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_776 TILs and counting..._ +_777 TILs and counting..._ --- @@ -142,6 +142,7 @@ _776 TILs and counting..._ - [Inspecting The Process Message Queue](elixir/inspecting-the-process-message-queue.md) - [List Functions For A Module](elixir/list-functions-for-a-module.md) - [Listing Files In IEx](elixir/listing-files-in-iex.md) +- [Match On A Map In A With Construct](elixir/match-on-a-map-in-a-with-construct.md) - [Pattern Matching In Anonymous Functions](elixir/pattern-matching-in-anonymous-functions.md) - [Quitting IEx](elixir/quitting-iex.md) - [Range Into List Using Comprehensions](elixir/range-into-list-using-comprehensions.md) diff --git a/elixir/match-on-a-map-in-a-with-construct.md b/elixir/match-on-a-map-in-a-with-construct.md new file mode 100644 index 0000000..4bd0b98 --- /dev/null +++ b/elixir/match-on-a-map-in-a-with-construct.md @@ -0,0 +1,25 @@ +# Match On A Map In A With Construct + +Many usage example of the +[`with`](https://hexdocs.pm/elixir/Kernel.SpecialForms.html#with/1) +construct show a series of matches on a tuple. + +```elixir +with {:ok, width} <- Map.fetch(opts, :width), + {:ok, height} <- Map.fetch(opts, :height) do + {:ok, width * height} +end +``` + +You can match on more than just tuples though. Here is how you might match +on a map. + +```elixir +with %{status_code: 200, body: body} <- HTTPoison.get!(url), + {:ok, decoded_body} <- Poison.decode(body) do + {:ok, decoded_body} +end +``` + +In fact, you have the full power of Elixir's pattern matching available to +you in your series of matches for a `with` construct.