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