small medium large xlarge

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

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

</details>

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.

My solution using default values:

``````defmodule MyList do
def sum(list, total \\ 0)
def sum([], total), do: total
end
``````

My solution.

``````defmodule Sum do
end

end
``````

My solution using nothing but plain old recursion:

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

``````

This is what occurred to me:

``````  def sum2([ head | [] ]), do: head
``````

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

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

You can always write `sum([accumulator | []])` as `sum([accumulator])`.

The solutions with a do: in the fuction defintions give a compile error in elixir 1.2. This compiles and works

``````defmodule MyList do
def sum([]) do
0
end
end
end
``````

Thought I was still supposed to maintain tail optimizations so here’s my solution

```defmodule MyList do
def sum([]), do: 0
def sum([ total | [] ]), do: total
def sum([ total | [ adder | tail ]]) do
sum([ total + adder | tail])
end
end
```

@stefan - This works for me in Elixir 1.2

``````defmodule MyList do
def sum([]), do: 0
end
``````

Just searched and found Enum module :-)

defmodule `Sum` do

def `sum(list),` do: `_sum(list)`

#private function

defp `_sum(list),` do: `Enum.sum(list)`

end

``````def suma([head|[]]), do: IO.puts head
``````
``````
defmodule Gosu do

#solution 1

def sum_1([]) do
0
end
end

#solution 2

def sum_2([]) do
0
end
def sum_2([x | []]) do
x
end

end

end

``````
You must be logged in to comment