small medium large xlarge

16 Jul 2013, 02:25
Dave Thomas (344 posts)
  • I defined our sum function to carry a partial total around as a second parameter. I did this so I could illustrate how to use accumulators to build values. The sum function can also be written without an accumulator. Can you do it?

A Possible Solution</summary>

defmodule MyList do
  def sum1([]),              do: 0
  def sum1([ head | tail ]), do: head + sum1(tail)

IO.puts MyList.sum1([1,2,3])       #=> 6
IO.puts MyList.sum1([1,2,3,4,5])   #=> 15


05 Dec 2013, 17:28
Tom van Neerijnen (1 post)

You can use the head as the accumualtor

defmodule MyList do
  def sum([accumulator| []]), do: accumulator
  def sum([accumulator, head | tail ]), do: sum2([ accumulator + head | tail ])


BTW How do you hide your “A Possible Solution”? You mentioned using “summary” in another post but a text search thru the markdown docs didn’t find any results for “summary” when I looked.

17 Sep 2014, 13:22
Peter C Marks (2 posts)

My solution using default values:

defmodule MyList do
  def sum(list, total \\ 0)
  def sum([], total), do: total
  def sum([head | tail], total), do: sum(tail, total + head)
20 Sep 2014, 04:46
lv cheng peng (4 posts)

My solution.

defmodule Sum do
  def sum([head | [head2 | tail]]) do
    sum([head + head2 | tail])

  def sum([head | []]), do: head
05 Dec 2014, 14:38
Lorenz Kitzmann (1 post)

My solution using nothing but plain old recursion:

defmodule MySum do
  def sum([]), do: 0
  def sum([ head | tail ]) do
    head + sum(tail)

24 Oct 2015, 20:35
Michael Johnston (6 posts)

This is what occurred to me:

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

is there a reason to prefer using def sum([]), do: 0 as the anchor func?

12 Nov 2015, 15:56
asymmetric . (4 posts)

Michael, in your solution no function matches the empty list.

You must be logged in to comment