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.

  You must be logged in to comment