-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanonymous_functions.exs
More file actions
47 lines (33 loc) · 917 Bytes
/
anonymous_functions.exs
File metadata and controls
47 lines (33 loc) · 917 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
defmodule Account do
def run_transaction(balance, amount, transaction) do
if balance <= 0 do
"Cannot perform any transaction"
else
transaction.(balance, amount)
end
end
end
deposit = fn(balance, amount) -> balance + amount end
withdrawal = fn(balance, amount) -> balance - amount end
Account.run_transaction(1000, 20, withdrawal)
|> IO.puts
Account.run_transaction(1000, 20, deposit)
|> IO.puts
Account.run_transaction(0, 20, deposit)
|> IO.puts
# pattern matching in anonymous functions
account_transaction = fn
(balance, amount, :deposit) -> balance + amount
(balance, amount, :withdrawal) -> balance - amount
end
account_transaction.(100, 40, :deposit)
|> IO.puts
#shorthand
deposit = &(&1 + &2)
Account.run_transaction(200, 40, deposit)
|> IO.puts
#inline shorthand
Account.run_transaction(1000, 20, &(&1 + &2))
|> IO.puts
Enum.map([1,2,3,4,5], &(&1 * 2))
|> IO.puts