1
I would like a function that, taking as a parameter a list, returns me the list somatic. Something like:
iex(0)> Recursive.sumAll([1, 3, 5])
# => 9
1
I would like a function that, taking as a parameter a list, returns me the list somatic. Something like:
iex(0)> Recursive.sumAll([1, 3, 5])
# => 9
1
Elixir has a very clever way of dealing with recursive functions, because the default lists are already chained or linked.
In Elixir the lists can be separated into two parts, head(head) and Tail(tail). Where the head is the first element of 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 see the equivalence with an operator ==
we will see that they are different ways of representing the same thing.
iex(0)> [1, 2] === [1 | [2]]
true
Important to say that this rule even applies to 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 assemble 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 entire list and add the previous head to the Tail head until we reach an empty list:
iex(9)> Recursive.sumAll([1,1,1])
3
Browser other questions tagged elixir
You are not signed in. Login or sign up in order to post.