Add new koans for comprehensions
Added to partially complete the "Koans for special forms" issue. https://github.com/elixirkoans/elixir-koans/issues/53
This commit is contained in:
36
lib/koans/20_comprehensions.ex
Normal file
36
lib/koans/20_comprehensions.ex
Normal file
@@ -0,0 +1,36 @@
|
||||
defmodule Comprehensions do
|
||||
use Koans
|
||||
|
||||
@intro "Comprehensions"
|
||||
|
||||
# A comprehension is made of three parts: generators, filters and collectables.
|
||||
|
||||
koan "Generators provide the values to be used in a comprehension" do
|
||||
# In the expression below, `n <- [1, 2, 3, 4]` is the generator.
|
||||
assert (for n <- [1, 2, 3, 4], do: n * n) == ___
|
||||
end
|
||||
|
||||
koan "Any enumerable can be a generator" do
|
||||
assert (for n <- 1..4, do: n * n) == ___
|
||||
end
|
||||
|
||||
koan "A generator specifies how to extract values from a collection" do
|
||||
collection = [["Hello","World"], ["Apple", "Pie"]]
|
||||
assert (for [a, b] <- collection, do: "#{a} #{b}") == ___
|
||||
end
|
||||
|
||||
koan "You can use multiple generators at once" do
|
||||
assert (for x <- [2, 4], y <- ["dogs", "cats"], do: "#{x} #{y}") == ___
|
||||
end
|
||||
|
||||
koan "Use a filter to reduce your work" do
|
||||
assert (for n <- [1, 2, 3, 4, 5, 6], n > 3, do: n) == ___
|
||||
end
|
||||
|
||||
koan "Add the result of a comprehension to an existing collection" do
|
||||
pies = ["Apple Pie"]
|
||||
pies = for x <- ["Pecan", "Pumpkin"], into: pies, do: "#{x} Pie"
|
||||
assert pies == ___
|
||||
end
|
||||
|
||||
end
|
18
test/koans/comprehensions_koans_test.exs
Normal file
18
test/koans/comprehensions_koans_test.exs
Normal file
@@ -0,0 +1,18 @@
|
||||
defmodule ComprehensionsTests do
|
||||
use ExUnit.Case
|
||||
import TestHarness
|
||||
|
||||
test "Comprehensions" do
|
||||
answers = [
|
||||
[1, 4, 9, 16],
|
||||
[1, 4, 9, 16],
|
||||
["Hello World", "Apple Pie"],
|
||||
["2 dogs", "2 cats", "4 dogs", "4 cats"],
|
||||
[4, 5, 6],
|
||||
["Apple Pie", "Pecan Pie", "Pumpkin Pie"],
|
||||
]
|
||||
|
||||
test_all(Comprehensions, answers)
|
||||
end
|
||||
|
||||
end
|
Reference in New Issue
Block a user