Skip to content

Instantly share code, notes, and snippets.

@follmann
Last active August 29, 2015 14:16
Show Gist options
  • Save follmann/2ad1c7b2a5ac93469986 to your computer and use it in GitHub Desktop.
Save follmann/2ad1c7b2a5ac93469986 to your computer and use it in GitHub Desktop.
Elixir (1.0.3) Pin Operator failing for pattern matches in for comprehensions

pin operator behaviour in match pattern

match with a tuple

iex(1)> x = 2
2
iex(2)> {^x, y} = {2, 1}
{2, 1}
iex(3)> y
1
iex(4)> {^x, y} = {3, 1}
** (MatchError) no match of right hand side value: {3, 1}

=> value of x is used in match pattern

match in for comprehension

iex(1)> values = [good: 1, good: 2, bad: 3, good: 4]
[good: 1, good: 2, bad: 3, good: 4]
iex(2)> for {:good, n} <- values, do: n
[1, 2, 4]
iex(3)> x = :good
:good
iex(4)> for {^x, n} <- values, do: n
[1, 2, 3, 4]

=> no error, but value of x is not used in the match pattern, it's silently ignored. I only became aware of it when the compiler warned that x wasn't used.

iex(5)> for {^x, n} <- values, do: {x, n}
[good: 1, good: 2, bad: 3, bad: 4]

=> returning the tuple in the for comprehension it shows that x is rebound

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment