What Is Elixir Closure — Tentamen Software Testing Blog

Elixir Closure

TL;DR

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

Closure

The closure is when Lambda references a variable memory location that is out of the scope of the lambda definition. We amplify the memory location because if the variable is rebind, the closure still references the original memory location. This is how immutability is implemented in closure.

In the above screenshot, you can see our iEx session with closures. We first defined variable tax with value for the Croatian price tax. Then we defined lambda closure that references tax value 0.25. When we call variable tax_in_dubrovnik with 50 hrk, we get a tax value of 12.5 hrk.

Then we rebind the tax variable to value 0.20, and we check closure immutability property by calling again tax_in_dubrovnik that returns again 12.5. We create new closure around tax value 0.20, tax_in_london and we get the amount of 10. We call closure again tax_in_dubrovnik and confirm that it is still a closure around the tax value of 0.25

Remember

  • closures are Lambdas
  • reference memory location, not variable itself

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

--

--

--

Founder of Tentamen, software testing agency.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

SYNONYM IN SQL SERVER

Boca Code celebrates the graduation of our first cohort!

CS373 Fall 2020: Lauren Jernigan

Common Kubernetes Misconfigurations and How to Fix Them

Lockdown: My transformation story

My congratulatory letter from SheCodeAfrica

CS373 Fall 2021, Week 12: Nitin Jain

MSBI Interview Questions: Update query, Conditional Split, Loop, Query

Parsing a long text and fetching desired pattern strings using SPARk SQL

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Karlo Smid

Karlo Smid

Founder of Tentamen, software testing agency.

More from Medium

An opinionated Elixir Style Guide #2

Recently in Ruby Core — April Edition

Comparing dates in Elixir

Elixir’s best practices: Achieve secure authentication