← docs.speechwave.live

Operators

Arrow-like operators

OperatorNameRead asWhere
=Match"matches"Everywhere
=>Map arrow"maps to"Map literals
->Clause arrow"then"case, cond, fn
<-Generator"drawn from"for, with
|>Pipe"then pass to"Anywhere

=: match

x = 42                         # bind x to 42
{:ok, result} = {:ok, 42}      # destructure: result is 42
{:ok, _} = some_function()     # assert success, discard value
^x = 42                        # pin: assert x is already 42

=>: map key-value separator

%{"id" => id}                  # string key (common in params)
%{name: "Tracy"}               # atom key shorthand (same as %{name: => "Tracy"})
%{1 => "one", 2 => "two"}     # any term as key

Atom keys get the key: value shorthand, so you rarely see => with atoms. String-keyed maps (from JSON, form params) always use =>.

->: clause arrow

Separates a pattern from its body. Read as "then."

# In case
case Talks.get_talk_by_slug(slug) do
  nil  -> {:ok, redirect(socket, to: "/")}
  talk -> {:ok, assign(socket, talk: talk)}
end

# In anonymous functions
fn x -> x * 2 end

# In cond
cond do
  count > 10 -> "many"
  count > 0  -> "some"
  true       -> "none"
end

<-: generator

Draws values from a collection or matches fallible results.

# In for comprehensions (loop)
for talk <- talks do
  talk.title
end

# In with (chain fallible operations)
with {:ok, user} <- find_user(email),
     {:ok, token} <- generate_token(user) do
  send_email(user, token)
else
  {:error, reason} -> handle_error(reason)
end

|>: pipe

# Passes left side as FIRST argument to right side
title |> String.downcase() |> String.trim()

# Equivalent to:
String.trim(String.downcase(title))

Other common operators

OperatorPurposeExample
^Pin (don't rebind)^x = 5 asserts x is 5
&Capture (make anonymous fn)& &1.name → fn x -> x.name end
<>String concatenation"hello" <> " world"
++List concatenation[1, 2] ++ [3, 4]
..Range1..10
&& / ||Boolean (short-circuit)user && user.name
and / orStrict booleanOnly accept true/false
! / notNegation!nil → true; not false → true
inMembershipx in [:a, :b, :c]
\\Default argumentdef foo(x \\ 42): x defaults to 42
::Bitstring spec<<x::integer-16>>

&&/|| accept any truthy/falsy value (only nil and false are falsy). and/or require strict true/false and raise otherwise.