I would like a function that, getting as a parameter a list, returns the list's summation. Something like:
iex(0)> Recursive.sumAll([1, 3, 5])
# => 9
I would like a function that, getting as a parameter a list, returns the list's summation. Something like:
iex(0)> Recursive.sumAll([1, 3, 5])
# => 9
Elixir has a very clever way of dealing with recursive functions, because lists are either linked or linked by default.
In Elixir lists can be separated into two parts, head and tail. Where the head is the first element in the list and the tail is all other subsequent elements.
Normal representation of a list:
iex(0)> a = [1, 2]
Representation head and tail:
iex(1)> a = [1 | [2]]
So much so that if we verify the equivalence with a ==
operator we will see that they are different ways of representing the same thing.
iex(0)> [1, 2] === [1 | [2]]
true
It's important to say that this rule is true even for lists that have only one element. Where Head is the only element and an empty list is tail:
iex(2)> [1] == [1 | []] # => true
With this knowledge, it's easy for us to build our recursion method:
defmodule Recursive do
# Definimos a condicional limitante da nossa função
def sumAll([]), do: 0
# Imprementamos a recursão de fato
def sumAll([head | tail]), do: head + sumAll(tail)
end
Our method will go through the whole list and add the previous head with the head of tail, until we come to an empty list:
iex(9)> Recursive.sumAll([1,1,1])
3