Skip to content

Instantly share code, notes, and snippets.

@vothane
Created October 11, 2015 20:52
Show Gist options
  • Save vothane/4d865be0817e6ae4e5b3 to your computer and use it in GitHub Desktop.
Save vothane/4d865be0817e6ae4e5b3 to your computer and use it in GitHub Desktop.
replacing template pattern with functions in Elixir
ExUnit.start
defmodule Grader do
def grade(grade) do
cond do
grade <= 5.0 and grade > 4.0 -> "A"
grade <= 4.0 and grade > 3.0 -> "B"
grade <= 3.0 and grade > 2.0 -> "C"
grade <= 2.0 and grade > 0 -> "D"
grade == 0 -> "F"
end
end
end
defmodule Printer do
def histogram(grades) do
grouped = Enum.group_by(grades, fn(grade) -> grade end)
counts = Enum.map(grouped, fn({k, v}) -> {k, length(v)} end)
end
end
defmodule Composer do
def compose(grader, printer) do
fn(grades) -> Printer.histogram(Enum.map(grades, grader)) end
end
end
defmodule GradePrintTest do
use ExUnit.Case
test "grade and print" do
g = Composer.compose(&Grader.grade/1, &Printer.histogram/1)
assert g.([2.3, 4.6, 2.4, 4.5, 1.2, 5.0, 4.9, 4.6, 3.8, 1.7, 4.6, 4.5, 4.4]) == [{"A", 8}, {"B", 1}, {"C", 2}, {"D", 2}]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment