All lessons

Power Tools: Anonymous Functions, Enum & the Pipe Operator

10 min · Elixir

Write inline functions, transform lists with Enum, and chain steps with |>.

Elixir · Power Tools: Anonymous Functions, Enum & the Pipe Operator0/5 cleared

Enemy 1 of 5

Anonymous functions

This code stores a small function in square that multiplies a number by itself, then calls it with 6 using a dot before the parentheses. Press Run to see it.

Why this works

Sometimes you need a small function just for one specific call site (passing a "rule" to another function) and defining a whole named module function for it would be overkill. An anonymous function is written `fn params -> body end` and, unlike a named function, is called with an explicit dot before the parentheses: `square.(6)`. That dot is a real syntactic requirement in Elixir, not a stylistic choice: it's what tells the compiler "call the function value bound to this name," as opposed to a named function call.

Anonymous functions are ordinary values: you can bind one to a variable, pass it as an argument, or return it from another function, exactly like a number or a string.

You
Binary Treant
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.