Lists and Patterns
Pattern discrimination allows to decompose lists:
let l = [6, 5, 3, 2]
mySum [] = 0
mySum (x:xs) = x + sum xs
mySum l
-- 16
We are recursively calling sum.
x = first element
xs = tail list (rest of the list)
Having fun? Other ways to do it:
- With a fold:
mySum = foldr (+) 0
- With a List Comprehension:
mySum xs = sum [x | x <- xs]
We say that e1 matches e2 if there exists a substitution for the variables of e1 that make it the same as e2.
Examples:
x:xsmatches[2, 5, 8]because[2, 5, 8]is2 : (5 : 8 : [])substitutingxwith2andxswith(5 : 8 : [])which is[5, 8].x:xsdoes not match[]because[]and:are different constructors.That's because
xcannot be a list, it has to be an element inside the list.x1:x2:xsmatches[2, 5, 8]substitutingx1with2,x2with5andxswith[8].x1:x2:xsmatches[2, 5]substitutingx1with2,x2with5andxswith[].
Note: The mechanism of matching is not the same as the unification (Prolog).