Let's say there is a simple function:
maximum' :: (Ord a) => [a] -> a
maximum' [] = error "maximum of empty list"
maximum' [x] = x
maximum' (x:xs) = max x (maximum' xs)
I understand the idea and what (x:xs) does. As it was explained in details here What do the parentheses signify in (x:xs) when pattern matching? but there is one little thing that I cannot get out of my head. Since cons: operator appends x to a list xs, why is it that x is the first element of function argument list and xs is the tail when we use (x:xs)??? as if (x:xs) calls head and tail on argument list.
The cons operator doesn't append, it prepends. That is
x : xs
produces a list that containsx
as its first element andxs
as the rest. Therefore the patternx : xs
likewise matches a list withx
as the first element andxs
as the rest.This is just an instance of the general pattern that the constructor for a type is both used to construct elements of that type and to deconstruct. If you wrote
you'd write
Except that lists are actually defined equivalently to
so, just as with other data types,
:
is used both to construct and to deconstruct nonempty lists.