brain/src/dev/elixir/lambda.md

33 lines
510 B
Markdown
Raw Normal View History

2020-03-28 09:32:24 +00:00
# Lamba or Anonymous Functions
## Create an anonymous function and bind it to a variable
### Simple one
```elixir
iex> func = fn -> IO.puts("Hello") end
#Function<21.126501267/0 in :erl_eval.expr/5>
iex> func.()
Hello
:ok
```
### One with arguments
```elixir
iex> func = fn t -> IO.puts(t) end
#Function<7.126501267/1 in :erl_eval.expr/5>
iex> func.("Hello")
Hello
:ok
```
Another solution is the `&` operator used as syntastic sugar
```elixir
iex> func = &(&1 + &2)
&:erlang.+/2
iex> func.(2, 2)
4
```