What Is Elixir Lambda And When To Use Them — Tentamen Software Testing Blog

Karlo Smid
2 min readSep 11, 2020
Elixir Lambda Function

TL;DR

In the previous post, we explained Elixir Strings. Let’s introduce Elixir First Class functions, Lambdas. This post is part of the functional language series, and it is based on the remarkable book Elixir In Action by Sasa Juric.

Lambda

Lambda is the eleventh letter of the Greek alphabet (Λ, λ), transliterated as ‘l.’

In Elixir, Lambda is First Class Function, a function that is not bound to a global name. Instead, we assign a lambda to a variable, so we could call it using that variable.

In the picture above, we define Croatian pdv lambda. Note how we call a lambda using . notation. This is needed to distinguish from getting named functions.

Lambda function could be passed as an argument to another function. An example is Enum.map` where lambda is called for each enumbrable element. In our case [1, 2, 3].

There is a shorter way to define a lambda using & the operator. The number represents the lambda attribute position.

I do not recommend using this shorten notation, because it makes your code hard to read, even for your future self.

Remember

  • lambda is created using fn keyword.
  • the dot notation
  • lambda as argument of another function
  • shorten notation using &

Originally published at https://blog.tentamen.eu on September 11, 2020.

--

--