defmodule Closures do @moduledoc """ A very simple example of closures in Elixir. This example explicitly and intentionally mirrors closu1.go and closu2.go The important differnece in Elixir is that once the function is defined, the values in the closure are set. Changing the value stored with a variable has no effect on the closure. This is by language design and follows immediately from immutability Author: gtowell Created Aug 2022 """ @doc """ Return a function that just add two numbers Realistically this only needs one line of code This is an example of currying. """ def clos1(aa) do retfun = fn bb -> aa+bb end retfun end @doc """ Return a function that just add two numbers Thanks to immutability the line aa=aa*2 is not relevant to the closure of the function defined on the previous line. """ def clos2(aa) do retfun = fn bb -> aa+bb end aa = aa*2 retfun end @doc """ Testing code for the two previous functions """ def main do fun17 = clos1(17) # Enum.each is weird in a function language. # in that the function invoked is exectued # for side effects ONLY Enum.each(1..5, fn v -> IO.puts("clos1 #{v} ==> #{fun17.(v)}" ) end) fun34 = clos2(17) Enum.each(1..5, fn v -> IO.puts("clos2 #{v} ==> #{fun34.(v)}") end ) end end Closures.main