Last active
December 20, 2015 01:09
-
-
Save nurugger07/6047430 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Mapper do | |
def map([], _func), do: [] | |
def map([head|tail], func) do | |
[func.(head) | map(tail, func)] | |
end | |
def mapsum([], _func), do: 0 | |
def mapsum([head|tail], func) do | |
func.(head) + mapsum(tail, func) | |
end | |
def max([]), do: 0 | |
def max([head|tail]) do | |
if head > max(tail), do: head, else: max(tail) | |
end | |
def span(from, to) do | |
if from <= to, do: [from | span(from + 1, to)], else: [] | |
end | |
end | |
ExUnit.start | |
defmodule TestMapper do | |
use ExUnit.Case | |
test "iterate a list and apply a function that adds 1" do | |
assert Mapper.map([1,2,3], &1 + 1) == [2,3,4] | |
end | |
test "iterate a list and apply a function that doubles" do | |
assert Mapper.map([1,2,3], fn(x) -> x*2 end) == [2,4,6] | |
end | |
test "iterate a list and apply a funciton to square" do | |
assert Mapper.map([1,2,3], fn(x) -> x*x end) == [1,4,9] | |
end | |
test "iterate a list and apply an addition function then sum" do | |
assert Mapper.mapsum([1,2,3], &1 + &1) == 12 | |
end | |
test "iterate a list and apply a multiplication function then sum" do | |
assert Mapper.mapsum([1,2,3], fn(n) -> n*n end) == 14 | |
end | |
# you can also pass atoms to test | |
test :max_in_list do | |
assert Mapper.max([4,8,5,7,3]) == 8 | |
end | |
test :span_a_valid_range do | |
assert Mapper.span(1, 5) == [1,2,3,4,5] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment