|
| 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 |
0 commit comments