Closures in Crystal
Crystal supports anonymous functions, which can form closures. Anonymous functions are useful when you want to define a function inline without having to name it.
To run the program, save it as closures.cr
and use the Crystal compiler:
In Crystal, closures are implemented using anonymous functions (also known as lambdas or Procs). The syntax ->
is used to define an anonymous function. The call
method is used to invoke the function.
The int_seq
function returns a closure that increments and returns a counter. Each time the closure is called, it increments its own i
variable and returns the new value.
The last feature of functions we’ll look at for now is recursion.