Skip to content

Commit

Permalink
Add new koans for comprehensions
Browse files Browse the repository at this point in the history
Added to partially complete the "Koans for special forms" issue.
elixirkoans/elixir-koans#53
  • Loading branch information
s-oram committed Sep 2, 2018
1 parent cca671e commit bc5a61e
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
36 changes: 36 additions & 0 deletions lib/koans/20_comprehensions.ex
Original file line number Diff line number Diff line change
@@ -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 changes: 18 additions & 0 deletions test/koans/comprehensions_koans_test.exs
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit bc5a61e

Please sign in to comment.