16 Jul 2013, 02:25
Dave_gnome_head_isolated_pragsmall

Dave Thomas (344 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</summary>

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

</details>

18 Oct 2013, 01:24
Generic-user-small

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-oculos-escuro_pragsmall

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
21 Sep 2014, 01:35
Generic-user-small

lv cheng peng (4 posts)


defmodule Mylist do
  def mapsum([head | [head2 | tail]], func) do
    mapsum([head + head2 | tail], func)
  end

  def mapsum([head | []], _func) do
    head
  end
end


24 Dec 2014, 19:56
Generic-user-small

Pierre Sugar (56 posts)

defmodule MyList do
  def map([], _func), do: []
  def map([head|tail], func), do: [func.(head) | map(tail, func)]

  def sums([]), do: 0
  def sums([head|tail]), do: head + sums(tail)

  def mapsum(list, func), do: map(list, func) |> sums
end
25 Mar 2015, 02:58
Generic-user-small

Scott Smith (8 posts)

Using an accumulator:

defmodule MyList do
  def mapsum(list, func), do: _mapsum(list, func, 0)
  defp _mapsum([], _func, accum), do: accum
  defp _mapsum([ head | tail ], func, accum) do
    _mapsum(tail, func, accum + func.(head))
  end
end
11 May 2015, 23:09
Generic-user-small

Aaron Malone (1 post)

Or to reuse existing MyList code:

def mapsum(list, func) do
  list |> map(func) |> sum
end
13 Jun 2015, 01:23
Jiqbl2rt_pragsmall

Gustavo Saiani (1 post)

Hi Dave, even though the mapsum call is perfect in the book, the call above the possible solution on top of this page no longer works:

iex> MyList.mapsum [1, 2, 3], &1 * &1
** (CompileError) iex:1: unhandled &1 outside of a capture
  You must be logged in to comment