Today I Learned

hashrocket A Hashrocket project

Matching *within* function parameter declaration

The below contains a "matching" expression within the function declaration:

iex > defmodule Hulk do
... > def print({1, a} = tt) do
... > IO.inspect(a)
... > IO.puts("**********")
... > IO.inspect(tt)
... > end
... > end

This allows the function access to the variable that was bound while matching and the full value passed in to the function. It returns:

iex > Hulk.print({1, 3})
3
**********
{1, 3}

This is particularly useful for Maps which is the only datatype to support partial matching (eg %{a: a} = %{a: 1, b: 2}) so that the unknown and unmatched portion of the map will be available.

This is a common idiom in pheonix while declaring actions in controllers:

def show(conn, %{"messenger" => messenger} = params) do

The above is from the pheonix docs

See More #elixir TILs
Looking for help? At Hashrocket, we 💜 Elixir! From our many Elixir client projects, to sponsoring the Chicago Elixir Meetup, to the source code for this application, we are invested in this community. Contact us today to talk about your Elixir project.