Skip to content

Commit 1084781

Browse files
committed
Add new koans for comprehensions
Added to partially complete the "Koans for special forms" issue. elixirkoans#53
1 parent 554ad1c commit 1084781

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

lib/koans/20_comprehensions.ex

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
defmodule Comprehensions do
2+
use Koans
3+
4+
@intro "Comprehensions"
5+
6+
# A comprehension is made of three parts: generators, filters and collectables.
7+
8+
koan "Generators provide the values to be used in a comprehension" do
9+
# In the expression below, `n <- [1, 2, 3, 4]` is the generator.
10+
assert (for n <- [1, 2, 3, 4], do: n * n) == ___
11+
end
12+
13+
koan "Any enumerable can be a generator" do
14+
assert (for n <- 1..4, do: n * n) == ___
15+
end
16+
17+
koan "A generator specifies how to extract values from a collection" do
18+
collection = [["Hello","World"], ["Apple", "Pie"]]
19+
assert (for [a, b] <- collection, do: "#{a} #{b}") == ___
20+
end
21+
22+
koan "You can use multiple generators at once" do
23+
assert (for x <- [2, 4], y <- ["dogs", "cats"], do: "#{x} #{y}") == ___
24+
end
25+
26+
koan "Use a filter to reduce your work" do
27+
assert (for n <- [1, 2, 3, 4, 5, 6], n > 3, do: n) == ___
28+
end
29+
30+
koan "Add the result of a comprehension to an existing collection" do
31+
pies = ["Apple Pie"]
32+
pies = for x <- ["Pecan", "Pumpkin"], into: pies, do: "#{x} Pie"
33+
assert pies == ___
34+
end
35+
36+
end
+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
defmodule ComprehensionsTests do
2+
use ExUnit.Case
3+
import TestHarness
4+
5+
test "Comprehensions" do
6+
answers = [
7+
[1, 4, 9, 16],
8+
[1, 4, 9, 16],
9+
["Hello World", "Apple Pie"],
10+
["2 dogs", "2 cats", "4 dogs", "4 cats"],
11+
[4, 5, 6],
12+
["Apple Pie", "Pecan Pie", "Pumpkin Pie"],
13+
]
14+
15+
test_all(Comprehensions, answers)
16+
end
17+
18+
end

0 commit comments

Comments
 (0)