Skip to content

Commit f637dff

Browse files
committed
Update and extend function koans
1 parent 8f09df6 commit f637dff

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

lib/koans/13_functions.ex

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,28 @@ defmodule Functions do
110110
assert result == ___
111111
end
112112

113+
koan "Pipes make data transformation pipelines readable" do
114+
numbers = [1, 2, 3, 4, 5]
115+
116+
result =
117+
numbers
118+
|> Enum.filter(&(&1 > 2))
119+
|> Enum.map(&(&1 * 2))
120+
|> Enum.sum()
121+
122+
assert result == ___
123+
124+
user_input = " Hello World "
125+
126+
cleaned =
127+
user_input
128+
|> String.trim()
129+
|> String.downcase()
130+
|> String.replace(" ", "_")
131+
132+
assert cleaned == ___
133+
end
134+
113135
koan "Conveniently keyword lists can be used for function options" do
114136
transform = fn str, opts ->
115137
if opts[:upcase] do
@@ -122,4 +144,16 @@ defmodule Functions do
122144
assert transform.("good", upcase: true) == ___
123145
assert transform.("good", upcase: false) == ___
124146
end
147+
148+
koan "Anonymous functions can use the & capture syntax for very concise definitions" do
149+
add_one = &(&1 + 1)
150+
multiply_by_two = &(&1 * 2)
151+
152+
result = 5 |> add_one.() |> multiply_by_two.()
153+
assert result == ___
154+
155+
# You can also capture existing functions
156+
string_length = &String.length/1
157+
assert string_length.("hello") == ___
158+
end
125159
end

test/koans/functions_koans_test.exs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,9 @@ defmodule FunctionsTests do
1919
100,
2020
1000,
2121
"Full Name",
22-
{:multiple, ["GOOD", "good"]}
22+
{:multiple, [24, "hello_world"]},
23+
{:multiple, ["GOOD", "good"]},
24+
{:multiple, [12, 5]}
2325
]
2426

2527
test_all(Functions, answers)

0 commit comments

Comments
 (0)