What does the ^ in elixir do? ex.“^name”. I tried googling, but google is horrible about looking up symbols. All found is that in math ^ is called a wedge.
3 Likes
Pin operator. Accesses an already bound variable in match clauses.
8 Likes
it is called the “pin operator”
Pattern matching - The Elixir programming language (half way in)
hth
5 Likes
Thanks for the name!
3 Likes
Thanks for the docs placement!
3 Likes
The pin operator fix the value of the variable, is ussefful in pattern match:
iex(1)> x=5
5
iex(2)> ^x=5
5
iex(3)> ^x=4
** (MatchError) no match of right hand side value: 4
iex(3)> {:ok,^x,y}={:ok,5,10}
{:ok, 5, 10}
iex(4)> {:ok,^x,y}={:ok,4,10}
** (MatchError) no match of right hand side value: {:ok, 4, 10}
iex(4)>
3 Likes
It’s also useful to know what you can’t do:
iex(1)> m = %{a: 1}
%{a: 1}
iex(2)> %{a: 1} = %{a: 1, b: 2}
%{a: 1, b: 2}
iex(3)> ^m = %{a: 1, b: 2}
** (MatchError) no match of right hand side value: %{a: 1, b: 2}
3 Likes
Also:
iex(1)> a = "a"
"a"
iex(2)> tuple = {"a"}
{"a"}
iex(3)> map = %{a: "a"}
%{a: "a"}
iex(4)> {^a} = tuple
{"a"}
iex(5)> {^map.a} = tuple
** (CompileError) iex:5: invalid argument for unary operator ^, expected an existing variable, got: ^map.
1 Like
Just remember that its behaviour may change in macros, for example in Ecto.Query.from/2
macro.
4 Likes