Pinned values as params in Elixir

Published September 27, 2018 by Toran Billups

In part 4 of my Elixir journey I wanted to show how pinned values work when they are used with functions.

Pinned Values

One example I found just fascinating in Elixir is how the pinned operator works along with matching when used as part of the function params.

    defmodule Robot do
      def speak(name, phrase) do
          (^name) -> "hello! #{name}, #{phrase}"
          (_) -> "sorry ... don't know this name"

You can follow along using IEx by throwing this script into a file called `foo.exs` and running the command below.

    iex -S mix run foo.exs

IEx provides an interactive session that you can use to learn the language. To invoke the function above pass both a name and phrase parameter.

    speaker = Robot.speak("toran", "you rawk!")

Next we can use the function returned by speak to generate a greeting with different inputs. Notice how pattern matching works with this new pinned parameter.

    IO.puts speaker.("toran")
    IO.puts speaker.("rando")

My shallow understanding of the pin operator before using them with functions was simply "do not re-bind this variable". In functions it works much the same way but in the example above you begin to see the real power of pattern matching. Using pattern matching and the pinned operator helps avoid what would otherwise be a conditional.

Note: the 2nd match having just an underscore acts like a fall through or default implementation.

Buy Me a Coffee

Twitter / Github / Email