Skip to main content

Command Palette

Search for a command to run...

#19: What are ^Pinned Values?

Published
1 min read
#19: What are ^Pinned Values?
S

I am a full-stack developer from Austria who has studied and worked in many countries including the UK, Australia, and the US. I have worked extensively with Ruby on Rails, React, and Typescript, and I am also building projects using Elixir and Phoenix.

Pinned values in Elixir allow you to reference existing variables within a pattern match. By using the pin operator ^, you can ensure that a variable's value is used as-is in the pattern match, rather than being treated as a new variable binding.

Basic Pinned Value:

# Define a variable
var = :match

# Using the pin operator to reference the existing variable in the pattern match
^var = :match
# Output: :match

# Attempting to match a different value will result in a MatchError
# ^var must match the existing value of var
^var = :no_match
# MatchError: no match of right hand side value: :no_match

Pinned Values in Tuple Matching:

# Define variables
var = :match
second = :other

# Using pinned values in tuple matching
[^var, second] = [:match, :other]
# Output: :other

Pinned Values with Maps:

# Define a map
map = %{a: 1}

# Using pinned values in map matching
^map = %{a: 1}
# Output: %{a: 1}

# Attempting to match a different map will result in a MatchError
^map = %{a: 1, b: 2}
# MatchError: no match of right hand side value: %{a: 1, b: 2}

Pinned values in Elixir provide a way to ensure that specific variables retain their values during pattern matching, offering control and predictability in pattern-matching scenarios.

More from this blog

Stephan Yu's Tech Journal

28 posts

This is my space for writing about tech-related topics that I find interesting. It allows me to share the things I have learned with the world.