O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Functions Can Return Functions

Here’s some strange code:

 
iex>​ fun1 = ​fn​ -> ​fn​ -> ​"Hello"​ ​end​ ​end
 
#Function<12.17052888 in :erl_eval.expr/5>​​​
 
iex>​ fun1.()
 
#Function<12.17052888 in :erl_eval.expr/5>​​​
 
iex>​ fun1.().()
 
"Hello"

The strange thing is the first line. It’s a little hard to read, so let’s spread it out.

 
fun1 = ​fn​ ->
 
fn​ ->
 
"Hello"
 
end
 
end

The variable fun1 is bound to a function. That function takes no parameters, and its body is a second function definition. That second function also takes no parameters, and it evaluates the string "Hello".

When we call the outer function (using fun1.()), it returns the inner function. When we call that (fun1.().()) the inner function is evaluated and “Hello” ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required