Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

[_] 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"]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading