Created
January 17, 2017 13:00
-
-
Save andresilveirah/1386a2137044f30f92ebee2b51fd4c30 to your computer and use it in GitHub Desktop.
An exercise to implement map, reduce and other iterating functions
This file contains 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 Map do | |
def map([], _), do: [] | |
def map([head|tail], fun), do: [fun.(head) | map(tail, fun)] | |
def reduce([], acumulator, _), do: acumulator | |
def reduce([head|tail], acumulator, fun), do: reduce(tail, fun.(head, acumulator), fun) | |
def mapsum(list, fun) do | |
map(list, fun) | |
|> reduce(0, &(&1 + &2)) | |
end | |
def max([head|tail]) do | |
compare = fn | |
a,b when a > b -> a | |
a,b when b >= a -> b | |
end | |
reduce([head|tail], head, compare) | |
end | |
end | |
list = [1,2,3] | |
squares = Map.map(list, &(&1 * &1)) | |
IO.puts Map.mapsum(squares, &(&1 + 1)) | |
IO.puts Map.max(list) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment