Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir - sum of list values with recursion

Tags:

erlang

elixir

Just trying to do simple sum of list values.

defmodule Mth do 

    def sum_list([]) do 
        0
    end

    def sum_list([H|T]) do
        H + sum_list(T)
    end

end

IO.puts Mth.sum_list([1, 2, 300]) 

But I get this error:

**(FunctionClauseError) no function clause matching in Mth.sum_list/1
    pokus.ex:3: Mth.sum_list([1, 2, 300])
    pokus.ex:14: (file)
    (elixir) src/elixir_lexical.erl:17: :elixir_lexical.run/2
    (elixir) lib/code.ex:316: Code.require_file/2**
like image 374
Krab Avatar asked Jul 14 '14 01:07

Krab


4 Answers

You need to use lowercase letters for variable and functions names. Identifiers starting with uppercase are reserved for modules:

defmodule Mth do 

  def sum_list([]) do 
    0
  end

  def sum_list([h|t]) do
    h + sum_list(t)
  end

end

iex> IO.puts Mth.sum_list([1, 2, 300])
303
:ok
like image 146
Chris McCord Avatar answered Nov 14 '22 23:11

Chris McCord


To improve upon Chris's solution, if you want your sum function to be tail recursive, you'd need to modify it a bit to be:

defmodule Mth do 
  def sum_list(list), do: do_sum_list(list, 0)

  defp do_sum_list([], acc),    do: acc
  defp do_sum_list([h|t], acc), do: do_sum_list(t, acc + h)
end

iex> Mth.sum_list([1, 2, 300])
303
like image 30
bitwalker Avatar answered Nov 14 '22 22:11

bitwalker


If you are going to use Enum.reduce you can go simpler:

defmodule Mth do
  def sum_list(list), do: Enum.reduce(list, 0, &(&1 + &2))
end
like image 20
emancu Avatar answered Nov 14 '22 23:11

emancu


Just for sake of completeness this would also work:

defmodule Mth do

  def sum_list(list), do: do_sum_list(list,0)

  defp do_sum_list(l,i_acc), do: Enum.reduce(l, i_acc, fn(x, accum) -> x + accum end)

end

I post this solely for reference for others who may find this question and it's answers.

like image 24
Onorio Catenacci Avatar answered Nov 14 '22 22:11

Onorio Catenacci