From 338e6abc21486d6e95d464c45c3096bc6b9529e2 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sat, 2 Jul 2016 16:27:23 -0500 Subject: [PATCH] Add Pattern Matching In Anonymous Functions as an elixir til --- README.md | 3 ++- ...pattern-matching-in-anonymous-functions.md | 25 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 elixir/pattern-matching-in-anonymous-functions.md diff --git a/README.md b/README.md index 9041e36..75e8a08 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really warrant a full blog post. These are mostly things I learn by pairing with smart people at [Hashrocket](http://hashrocket.com/). -_442 TILs and counting..._ +_443 TILs and counting..._ --- @@ -86,6 +86,7 @@ _442 TILs and counting..._ - [Execute Raw SQL In An Ecto Migration](elixir/execute-raw-sql-in-an-ecto-migration.md) - [Expose Internal Representation](elixir/expose-internal-representation.md) - [List Functions For A Module](elixir/list-functions-for-a-module.md) +- [Pattern Matching In Anonymous Functions](elixir/pattern-matching-in-anonymous-functions.md) - [Quitting IEx](elixir/quitting-iex.md) - [Replace Duplicates In A Keyword List](elixir/replace-duplicates-in-a-keyword-list.md) - [Word Lists For Atoms](elixir/word-lists-for-atoms.md) diff --git a/elixir/pattern-matching-in-anonymous-functions.md b/elixir/pattern-matching-in-anonymous-functions.md new file mode 100644 index 0000000..db68b7d --- /dev/null +++ b/elixir/pattern-matching-in-anonymous-functions.md @@ -0,0 +1,25 @@ +# Pattern Matching In Anonymous Functions + +Pattern matching shows up everywhere in Elixir, even where you may not be +expecting it. When declaring an anonymous function, you can use pattern +matching against different sets and shapes of input parameters to invoke +different behaviors. + +Here is an example of how you might use this: + +```ex +> handle_result = fn + {:ok, result} -> IO.puts "The result is #{result}" + :error -> IO.puts "Error: couldn't find anything" +end +#Function<6.50752066/1 in :erl_eval.expr/5> + +> Map.fetch(%{a: 1}, :a) |> handle_result.() +The result is 1 +:ok +> Map.fetch(%{a: 1}, :b) |> handle_result.() +Error: couldn't find anything +:ok +``` + +[source](https://elixirschool.com/lessons/basics/functions#pattern-matching)