Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
What does `x :: xs` pattern matching mean in Elm?

What does x :: xs pattern matching mean in Elm?

:: is the list prepend operator in Elm.

3 :: 2 :: 1 :: []

is equivalent to

[3,2,1]

we can pattern match on particular series of prepended elements. Why?

Building our own list

Let's try building our own list.

type MyList a = Prepend a (MyList a) | EmptyList

instatiating such a list would look like:

list = Prepend 3 (Prepend 2 (Prepend 1 EmptyList))

Pattern matching

Now we can pattern match like:

case list of
  Prepend x (Prepend y (Prepend z rest))) -> -- a list with at least 3 elements
  Prepend x (Prepend y rest) -> -- a list with at least 2 elements
  Prepend x rest -> -- a list with at least 1 element
  EmptyList -> -- a list with no elements

Look familiar?

The core List equivalent would look like:

case list of
  x :: y :: z :: rest -> -- a list with at least 3 elements
  x :: y :: rest -> -- a list with at least 2 elements
  x :: rest -> -- a list with at least 1 element
  [] -> -- a list with no elements
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment