mirror of
https://github.com/jbranchaud/til
synced 2026-01-04 15:48:01 +00:00
Add Defining Multiple Clauses In An Anonymous Function 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/).
|
||||
|
||||
_518 TILs and counting..._
|
||||
_519 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -98,6 +98,7 @@ _518 TILs and counting..._
|
||||
- [Create A Date With The Date Sigil](elixir/create-a-date-with-the-date-sigil.md)
|
||||
- [Creating A PID](elixir/creating-a-pid.md)
|
||||
- [Creating Indexes With Ecto](elixir/creating-indexes-with-ecto.md)
|
||||
- [Defining Multiple Clauses In An Anonymous Function](elixir/defining-multiple-clauses-in-an-anonymous-function.md)
|
||||
- [Determine The Latest Release Of A Hex Package](elixir/determine-the-latest-release-of-a-hex-package.md)
|
||||
- [Do You Have The Time?](elixir/do-you-have-the-time.md)
|
||||
- [Do You Have The Time? - Part 2](elixir/do-you-have-the-time-part-2.md)
|
||||
|
||||
29
elixir/defining-multiple-clauses-in-an-anonymous-function.md
Normal file
29
elixir/defining-multiple-clauses-in-an-anonymous-function.md
Normal file
@@ -0,0 +1,29 @@
|
||||
# Defining Multiple Clauses In An Anonymous Function
|
||||
|
||||
Anonymous functions often take the approach of doing a single thing with the
|
||||
inputs, regardless of their shape or values. There is no need to limit
|
||||
ourselves though. The same pattern matching that we use all over our Elixir
|
||||
programs can be utilized to define multiple clauses in an anonymous function
|
||||
as well.
|
||||
|
||||
Consider the following example:
|
||||
|
||||
```elixir
|
||||
iex> my_function = fn
|
||||
{:ok, x} -> "Everything is ok: #{x}"
|
||||
{:error, x} -> "There was an error: #{x}"
|
||||
end
|
||||
#Function<6.52032458/1 in :erl_eval.expr/5>
|
||||
```
|
||||
|
||||
We can then invoke our anonymous function using the bound variable to see
|
||||
what results we get with different kinds of inputs.
|
||||
|
||||
```
|
||||
iex> my_function.({:ok, 123})
|
||||
"Everything is ok: 123"
|
||||
iex> my_function.({:error, "be warned"})
|
||||
"There was an error: be warned"
|
||||
```
|
||||
|
||||
[source](http://stackoverflow.com/a/18023790/535590)
|
||||
Reference in New Issue
Block a user