Skip to content

Instantly share code, notes, and snippets.

@stockwellb
Created June 7, 2016 03:31
Show Gist options
  • Save stockwellb/8e455639abca2e4ed32c7f331f40b31d to your computer and use it in GitHub Desktop.
Save stockwellb/8e455639abca2e4ed32c7f331f40b31d to your computer and use it in GitHub Desktop.
An exercise in map, reduce, length for lists
defmodule ListOps do
def length(list) do
reduce(list,0,fn(item,acc) -> acc + 1 end)
end
def reduce([], acc, _) do
acc
end
def reduce([h|t], acc, fun) do
reduce(t,fun.(h,acc),fun)
end
def map(list, fun) do
reduce(list,[],fn(item, acc) ->
[fun.(item)|acc]
end) |> Enum.reverse
end
end
ExUnit.start
defmodule ListOpsTest do
use ExUnit.Case, async: true
test "length of empty list" do
assert 0 == ListOps.length([])
end
test "length of list 1" do
assert 1 == ListOps.length([1])
end
test "length of list 10" do
assert 10 == ListOps.length([1,2,3,4,5,6,7,8,9,10])
end
test "reduce int list" do
assert 55 == ListOps.reduce([1,2,3,4,5,6,7,8,9,10],0,fn(item, acc) ->
acc + item
end)
end
test "treat reduce like map" do
assert [2,4,6] == ListOps.reduce([1,2,3],[],fn(item, acc) ->
acc ++ [item * 2]
end)
end
test "map ints + 1" do
assert [2,3,4] == ListOps.map([1,2,3], &(&1 + 1))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment