Skip to content

Instantly share code, notes, and snippets.

@JoelQ
Last active December 5, 2021 16:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoelQ/916c1e4fe96408b4057d36908c779c90 to your computer and use it in GitHub Desktop.
Save JoelQ/916c1e4fe96408b4057d36908c779c90 to your computer and use it in GitHub Desktop.
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