16 Jul 2013, 02:25
Dave_gnome_head_isolated_pragsmall

Dave Thomas (338 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
defmodule MyList do
  def sum1([]),              do: 0
  def sum1([ head | tail ]), do: head + sum1(tail)
end

IO.puts MyList.sum1([1,2,3])       #=> 6
IO.puts MyList.sum1([1,2,3,4,5])   #=> 15
05 Dec 2013, 17:28
Generic-user-small

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 ])

end

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
Generic-user-small

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)
end
20 Sep 2014, 04:46
Generic-user-small

lv cheng peng (4 posts)

My solution.

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

  def sum([head | []]), do: head
end
05 Dec 2014, 14:38
Generic-user-small

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)
  end
end

  You must be logged in to comment