16 Jul 2013, 02:25 Dave Thomas (338 posts) Write a function mapsum that takes a list and a function. It applies the function to each element of the list, and then sums the result, so iex> MyList.mapsum [1, 2, 3], &1 * &1 14 A Possible Solution defmodule MyList do def mapsum([], _fun), do: 0 def mapsum([ head | tail ], fun), do: fun.(head) + mapsum(tail, fun) end IO.puts MyList.mapsum([1, 2, 3], &1 * &1) #=> 14 18 Oct 2013, 01:24 ian xiong (1 post) defmodule MyList do def mapsum([], _), do: 0 def mapsum([head | tail], fun) do mapsum(tail, fun.(head), fun) end defp mapsum([head | tail], value, fun) do mapsum(tail, value + fun.(head), fun) end defp mapsum([], value, _), do: value end 28 Dec 2013, 14:44 Hugo Pessoa de Baraúna (3 posts) defmodule MyList do def map([], _func), do: [] def map([ head | tail ], func), do: [ func.(head) | map(tail, func) ] def reduce([], value, _) do value end def reduce([head | tail], value, fun) do reduce(tail, fun.(head, value), fun) end def mapsum(list, fun) do map(list, fun) |> reduce(0, &(&1 + & 2)) end end You must be logged in to comment