small medium large xlarge

Dave_gnome_head_isolated_pragsmall
16 Jul 2013, 02:25
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>

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


Generic-user-small
24 Dec 2014, 19:56
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
Generic-user-small
25 Mar 2015, 02:58
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
Generic-user-small
11 May 2015, 23:09
Aaron Malone (1 post)

Or to reuse existing MyList code:

def mapsum(list, func) do
  list |> map(func) |> sum
end
Jiqbl2rt_pragsmall
13 Jun 2015, 01:23
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