Let's see how
List is used in the context of pattern matching.
This is a pre-requirement to talk about recursion later on.
First we have to talk about how
List can be created and modified.
Everything is immutable which is why we always create a new
List, we don't update the previous one.
A few new operator today:
Nil: not really an operator, but it describe an empty list, it is a short cut for
::: to add an element at the start of a
List, which is why to create a
Listusing this operator, we have to finish by
Nil. We actually prepend element to an empty list.
+:: to prepend an element to the
List. Same as
:+: to append an element at the end of a
If know that
:+ can be confusing but you simply have to remember that
: is towards the
Pattern matching now
:: we can extract head element(s) from the List.
For instance, we can
case head :: tail => to extract the first element of the list. We can also do
case a :: b :: tail => to extract the two first element of the list. We can continue with as many as we would like.
Similarly to all the other pattern matching construct, we can add conditions to all those patterns. Either by adding
if at the end or by replacing a value name by a literal value, for instance:
case 1 :: tail => will match on any list that start by a
case 1 :: Nil => will match on a list containing one element being