What is the meaning of the `[_]` pattern in Haskell?

Viewed 103

When creating pattern matches in Haskell, does the following pattern match:

function [_] = []

mean the same as:

function (x:xs) = []

If not, what does the [_] pattern mean?

1 Answers

[_] matches a list with one element; x:xs matches any non-empty list, with the side effect of binding the head to x and the tail to xs.

[_] is equivalent to (_:[]).

Given

f x = case x of 
        [_] -> "singleton"
        [] -> "empty"
        otherwise -> "nonempty"

then

> print $ map f [[], [1], [1,2]]
["empty","singleton","nonempty"]
Related