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

Time:07-20

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?

CodePudding user response:

[_] 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