Anonymous Functions - Elixir

In Elixir, functions are first class citizens. What does it mean? It means that functions can be
  1. Assigned to variables
  2. Passed around as arguments to other functions
Anonymous functions has no name and no modules. We can create them with syntax fn ->

my_function = fn(param) -> "Passed param: #{param}" end

In order to invoke this function we must use the .() syntax


Named function can take anonymous functions as argument. This helps promote decoupling. A sample example is shown below

defmodule Maths do
calculate(first, second, operation) do
operation.(first, second)

multiply = fn(first, second) -> first * second end
addition = fn(first, second) -> first + second end

sum = Maths.calculate(2, 5, addition)
product = Maths.calculate(2, 5, multiply)

The expected value for sum and product will be 7 and 10 respectively. With this example we can conclude that anonymous functions can be passed as arguments to other functions just like any other data type.

Similar to named function, anonymous functions can also be split into multiple clauses using pattern matching.

Maths = fn
(first, second, :addition) -> first + second
(first, second, :multiply) -> first * second

Maths.(2, 5, :addition)
Maths.(2, 5, :multiply)

In first execution of Maths.(2, 5, :addition), pattern matching will identify addition atom and will add the two number. Similarly for second call it will identify the atom and will multipy both the numbers.

Shorthand Syntax

The & operator is used to create helper functions in a short and concise way. Our addition function as mentioned in above examples can be re-written as below

addition = &(&1 + &2)

This version of anonymous function is often found used inline as arguments to other functions. One example would be function which is part of Elixir's standard library. It returns a list where each item is the result og invoking a function on each corresponding item of enumerable[1, 2, 3, 4], &(&1 * &1))

The output for this will be square of each number passed in first argument i.e. 1, 4, 9, 16


Popular posts from this blog

Google Chrome Extension - ReactJS

Angular JS, Require JS and Karma