defmodule Closu do @moduledoc """ Several examples of closures in elixir """ @doc """ A small example of currying and closures the variable val is in the closure of the returned function """ def curry_plus (val) do fn (ival) -> val+ival end end @doc """ Because vars are immutable in Elixir, "changing" the value of val after defining the function stored in aa has no effect """ def curry_plus_ch (val) do aa = fn (ival) -> val+ival end val = 100 IO.puts val aa end @doc """ Closures work on received functions just like on returned functions """ def recv_func(fnn, val) do IO.puts fnn.(val) end def main do aa = Closu.curry_plus(7) bb = Closu.curry_plus(42) IO.puts aa.(6) IO.puts bb.(6) aaa = Closu.curry_plus_ch(7) bbb = Closu.curry_plus_ch(42) IO.puts "val ch #{aaa.(6)}" IO.puts "val ch #{bbb.(6)}" ff = fn (cc) -> aa.(cc)*cc end recv_func(ff, 5) recv_func(bb, 5) end end Closu.main