mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 07:08:01 +00:00
Add Pattern Matching In Anonymous Functions as an elixir til
This commit is contained in:
@@ -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)
|
||||
|
||||
25
elixir/pattern-matching-in-anonymous-functions.md
Normal file
25
elixir/pattern-matching-in-anonymous-functions.md
Normal file
@@ -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)
|
||||
Reference in New Issue
Block a user