() {Functional Programming}
Closure#
Lexical Scoping#
To understand closure let's first take a look at Lexical scoping using example below:
testScope creates local variable test and instance of function insideScope .
insideScope() displays value of test variable,which is declared in its parent function.
Variable test is not declared in insideScope , still it is accessible.. which is referred as Lexical Scope.
Closer to Closure#
Closure is a function enclosed within another function having some variable(state). Example:
Call to outerFunction is returning innerFunction (‘closure’ ) which captures the variable a.
Variable a can be accessed only by innerFunction (in read-only mode) outside its Lexical Scope so it can be referred as variable private to innerFunctionHigher-Order Functions
function are first-class objects!#
In cafe, functions are first-class objects. Thus, a function can be assigned to a variable, can be passed as an argument & can be returned inside a function.
When a function is declared, internally a Function object is created and is assigned to variable.
Thus, it becomes possible to use functions as any other variables.
Anonymous Function#
In cafe anonymous function can be implemented using syntax below: Syntax
Example: