How to define persistent matrix variable inside the Scilab function? - scilab

I have been developing a Scilab function where I need to have persistent variable of the matrix type. Based on my similar question I have chosen the same approach. Below is the code I have used for test of this approach.
function [u] = FuncXYZ(x)
global A;
global init;
if init == 0 then
init = 1;
A = eye(4, 4);
endif
u = A(1, 1);
endfunction
As soon as I have integrated the function inside my Xcos simulation I have been surprised that I see "0" at the output of the scifunc_block_m.
Nevertheless I have found that in case I use below given command for "return" from the function
u = A(3, 3);
the function returns really the expected "1". Additionaly if I take a look at the Variable Browser on the top right corner of the Scilab window I can't se the expected A 4x4 item. It seems that I am doing something wrong.
Can anybody give me an advice how to define a persistent variable of the matrix type inside the Scilab function?
Thanks in advance for any ideas.

Global variables are by default initialized with an empty matrix. Hence, you should detect first call with isempty()
function [u] = FuncXYZ(x)
global A;
global init;
if isempty(init)
init = 1;
A = eye(4, 4);
end
u = A(1, 1);
endfunction
BTW, your code is incorrect, there is no endif in Scilab.

Related

Julia create function from string

In Julia v1.01 I would like to create a function from a string.
Background: In a numerical solver, a testcase is defined via a JSON file. It would be great if the user could specify the initial condition in string form.
This results in the following situation: Assume we have (from the JSON file)
fcn_as_string = "sin.(2*pi*x)"
Is there a way to convert this into a function fcn such that I can call
fcn(1.0) # = sin.(2*pi*1.0)
Performance is not really an issue, as the initial condition is evaluated once and then the actual computation consumes most of the time.
Can't get my code displayed correctly in a comment so here's a quick fix for crstnbr's solution
function fcnFromString(s)
f = eval(Meta.parse("x -> " * s))
return x -> Base.invokelatest(f, x)
end
function main()
s = "sin.(2*pi*x)"
f = fcnFromString(s)
f(1.)
end
julia> main()
-2.4492935982947064e-16
The functions Meta.parse and eval allow you to do this:
fcn_as_string = "sin.(2*pi*x)"
fcn = eval(Meta.parse("x -> " * fcn_as_string))
#show fcn(1.0)
This return -2.4492935982947064e-16 (due to rounding errors).

How to use boost::compute::atan2?

I would like to compute the phase of a complex number using boost::compute
here is my attempt, I expect the result to be equal to atan2(0.5f):
namespace bc = boost::compute;
bc::vector<std::complex<float>> vec{ {1.0f, 2.0f} };
bc::vector<float> result(1);
bc::transform(vec.begin(), vec.end(), result.begin(), bc::atan2<float>());
but I get a compilation error claiming "Non-unary function invoked one argument"
boost::compute's atan2 would appear to be a binary function just like std::atan2.
I'm assuming you're trying to obtain the phase angle of your complex number? The standard C++ function for this would be std::arg() - I don't see this one being defined in boost::compute, though I might have missed it.
If arg() is indeed missing, you're quite right it's implemented via atan2 - you'll need to extract the imaginary (boost::compute::imag()) and real (boost::compute::real()) components first though, and pass them as individual arguments to atan2.
I think you can also use Boost.Compute's lambda expressions for this:
bc::vector<float2> input{ {1.0f, 2.0f}, {3.0f, 4.0f}, {5.0f, 6.0f} };
bc::vector<float> output(3);
using boost::compute::lambda::atan2;
using boost::compute::_1;
using boost::compute::lambda::get;
bc::transform(
float2_input.begin(),
float2_input.end(),
float_output.begin(),
atan2(get<1>(_1), get<0>(_1)),
queue
);
float2 is bassically a complex in Boost.Compute. You can also check test_lambda.cpp.
I found a way to make it work.
stage 1: allocate 2 vectors:
bc::vector<std::complex<float>> vec{ {1.0f, 2.0f}, {3.0f, 4.0f}, {5.0f, 6.0f} };
bc::vector<float> result(3);
stage 2: interpret the complex vector as a float buffer iterator
buffer_iterator is quite useful when you have a strongly typed vector and would like to pass it to an algorithm as a different type.
auto beginf = bc::make_buffer_iterator<float>(vec.get_buffer(), 0);
auto endf = bc::make_buffer_iterator<float>(vec.get_buffer(), 6); // note end point to final index + 1
stage 3: define strided iterators so that we can use the same buffer as the argument for tan2. each iterator iterates the buffers in strides of 2 indices, and they supply tan2 with interleaved access to the buffer:
auto begin_a = bc::make_strided_iterator(beginf + 1, 2); // access imaginary part
auto end_a = bc::make_strided_iterator_end(beginf + 1, endf , 2);
auto begin_b = bc::make_strided_iterator(beginf, 2); // access real part
finally, call transform:
bc::transform(begin_a, end_a, begin_b, result.begin(), bc::atan2<float>()); // atan(b/a)
bc::system::default_queue().finish();

How to use Octave/Matlab Inline function in Scilab

How to use this Octave/Matlab inline function in Scilab?
u = inline('t>=0') where t=0:0.001:1.
y = (u(t-0.2)-u(t-0.3))
I tried it in Scilab as
deff('[u]=f(t)','u=(t>=0)')
But I am getting an error as "invalid index" in determining 'y'.
Unlike in Matlab, invoking (t>=0) gives you a boolean vector, its entries are True or False. Since you want 1s and 0s, you need bool2s to convert from boolean to integers:
deff('[u]=f(t)','u=bool2s(t>=0)')
After that you can invoke the function like any other:
t = 0:0.001:1
y = u(t-0.2)-u(t-0.3)
plot(t,y)
Personally, I never see the need for inline functions in Scilab. If I were writing the above, I would declare the function normally:
function y = u(t)
y = bool2s(t>=0)
endfunction
Unlike Matlab, Scilab allows you to have such functions appear wherever you want them in the script.

Scilab double integral

Below is the code for my program. I'm attempting to find the value of the integral of 1/ln(x), and then evaluate the integral from 0 to x, with this as the integrand. I'm not exactly sure what I'm doing wrong, but I am quite new to Scilab.
t = input("t");
x=10; while x<t, x=x+10,
function y=f(x), y=(1/(log (x))), endfunction
I=intg(2,x,f);
function z=g(x), z=I, endfunction
W = intg(0,x,z);
W
end
I'm not entirely sure on what you are trying to achieve, but I reformatted your code and added some suggestions to documentation.
Maybe it will help you in finding the answer.
While loop
You can convert your while loop to a for loop
Your code
x=10;
while x<t
x=x+10
//some code
end
Could be
for x=10:10:t
//some code
end
Functions
In your code, you redeclare the two functions every single iteration of the while loop. You could declare them outside the while loop and call them inside the loop.
Reformatted
t = input("Please provide t: ");
// The function of 1/ln(x)
function y=f(x), y=1/log(x), endfunction
// Every time g(x) is called the current value of I is returned
function z=g(x), z=I, endfunction
for x=10:10:t
//Find definite integral of function f from 2 to x
I = intg(2,x,f);
//Find definite integral of I from 0 to x
W = intg(0,x,g);
disp( string(W) );
end
I know the question is porbably outdated; but the topic is still active. And I was looking for a code with double integral.
Here, it looks strange to use "intg" just to calculate the area of the rectangle defined by its diagonal ((0,0), (x,I)): the result is just x*I...
May be the initial aim was to consider "I" as a function of "x" (but in this case there is a convergence problem at x=1...); so restricting the integration of "I" to something above 1 gives the following code:
x=10:10:100;W2=integrate('integrate(''1/log(x2)'',''x2'',2,x1)','x1',1.001,x);
Note the use of integration variables x1 and x2, plus the use of quotes...

What is a 'Closure'?

I asked a question about Currying and closures were mentioned.
What is a closure? How does it relate to currying?
Variable scope
When you declare a local variable, that variable has a scope. Generally, local variables exist only within the block or function in which you declare them.
function() {
var a = 1;
console.log(a); // works
}
console.log(a); // fails
If I try to access a local variable, most languages will look for it in the current scope, then up through the parent scopes until they reach the root scope.
var a = 1;
function() {
console.log(a); // works
}
console.log(a); // works
When a block or function is done with, its local variables are no longer needed and are usually blown out of memory.
This is how we normally expect things to work.
A closure is a persistent local variable scope
A closure is a persistent scope which holds on to local variables even after the code execution has moved out of that block. Languages which support closure (such as JavaScript, Swift, and Ruby) will allow you to keep a reference to a scope (including its parent scopes), even after the block in which those variables were declared has finished executing, provided you keep a reference to that block or function somewhere.
The scope object and all its local variables are tied to the function and will persist as long as that function persists.
This gives us function portability. We can expect any variables that were in scope when the function was first defined to still be in scope when we later call the function, even if we call the function in a completely different context.
For example
Here's a really simple example in JavaScript that illustrates the point:
outer = function() {
var a = 1;
var inner = function() {
console.log(a);
}
return inner; // this returns a function
}
var fnc = outer(); // execute outer to get inner
fnc();
Here I have defined a function within a function. The inner function gains access to all the outer function's local variables, including a. The variable a is in scope for the inner function.
Normally when a function exits, all its local variables are blown away. However, if we return the inner function and assign it to a variable fnc so that it persists after outer has exited, all of the variables that were in scope when inner was defined also persist. The variable a has been closed over -- it is within a closure.
Note that the variable a is totally private to fnc. This is a way of creating private variables in a functional programming language such as JavaScript.
As you might be able to guess, when I call fnc() it prints the value of a, which is "1".
In a language without closure, the variable a would have been garbage collected and thrown away when the function outer exited. Calling fnc would have thrown an error because a no longer exists.
In JavaScript, the variable a persists because the variable scope is created when the function is first declared and persists for as long as the function continues to exist.
a belongs to the scope of outer. The scope of inner has a parent pointer to the scope of outer. fnc is a variable which points to inner. a persists as long as fnc persists. a is within the closure.
Further reading (watching)
I made a YouTube video looking at this code with some practical examples of usage.
I'll give an example (in JavaScript):
function makeCounter () {
var count = 0;
return function () {
count += 1;
return count;
}
}
var x = makeCounter();
x(); returns 1
x(); returns 2
...etc...
What this function, makeCounter, does is it returns a function, which we've called x, that will count up by one each time it's called. Since we're not providing any parameters to x, it must somehow remember the count. It knows where to find it based on what's called lexical scoping - it must look to the spot where it's defined to find the value. This "hidden" value is what is called a closure.
Here is my currying example again:
function add (a) {
return function (b) {
return a + b;
}
}
var add3 = add(3);
add3(4); returns 7
What you can see is that when you call add with the parameter a (which is 3), that value is contained in the closure of the returned function that we're defining to be add3. That way, when we call add3, it knows where to find the a value to perform the addition.
First of all, contrary to what most of the people here tell you, closure is not a function! So what is it?
It is a set of symbols defined in a function's "surrounding context" (known as its environment) which make it a CLOSED expression (that is, an expression in which every symbol is defined and has a value, so it can be evaluated).
For example, when you have a JavaScript function:
function closed(x) {
return x + 3;
}
it is a closed expression because all the symbols occurring in it are defined in it (their meanings are clear), so you can evaluate it. In other words, it is self-contained.
But if you have a function like this:
function open(x) {
return x*y + 3;
}
it is an open expression because there are symbols in it which have not been defined in it. Namely, y. When looking at this function, we can't tell what y is and what does it mean, we don't know its value, so we cannot evaluate this expression. I.e. we cannot call this function until we tell what y is supposed to mean in it. This y is called a free variable.
This y begs for a definition, but this definition is not part of the function – it is defined somewhere else, in its "surrounding context" (also known as the environment). At least that's what we hope for :P
For example, it could be defined globally:
var y = 7;
function open(x) {
return x*y + 3;
}
Or it could be defined in a function which wraps it:
var global = 2;
function wrapper(y) {
var w = "unused";
return function(x) {
return x*y + 3;
}
}
The part of the environment which gives the free variables in an expression their meanings, is the closure. It is called this way, because it turns an open expression into a closed one, by supplying these missing definitions for all of its free variables, so that we could evaluate it.
In the example above, the inner function (which we didn't give a name because we didn't need it) is an open expression because the variable y in it is free – its definition is outside the function, in the function which wraps it. The environment for that anonymous function is the set of variables:
{
global: 2,
w: "unused",
y: [whatever has been passed to that wrapper function as its parameter `y`]
}
Now, the closure is that part of this environment which closes the inner function by supplying the definitions for all its free variables. In our case, the only free variable in the inner function was y, so the closure of that function is this subset of its environment:
{
y: [whatever has been passed to that wrapper function as its parameter `y`]
}
The other two symbols defined in the environment are not part of the closure of that function, because it doesn't require them to run. They are not needed to close it.
More on the theory behind that here:
https://stackoverflow.com/a/36878651/434562
It's worth to note that in the example above, the wrapper function returns its inner function as a value. The moment we call this function can be remote in time from the moment the function has been defined (or created). In particular, its wrapping function is no longer running, and its parameters which has been on the call stack are no longer there :P This makes a problem, because the inner function needs y to be there when it is called! In other words, it requires the variables from its closure to somehow outlive the wrapper function and be there when needed. Therefore, the inner function has to make a snapshot of these variables which make its closure and store them somewhere safe for later use. (Somewhere outside the call stack.)
And this is why people often confuse the term closure to be that special type of function which can do such snapshots of the external variables they use, or the data structure used to store these variables for later. But I hope you understand now that they are not the closure itself – they're just ways to implement closures in a programming language, or language mechanisms which allows the variables from the function's closure to be there when needed. There's a lot of misconceptions around closures which (unnecessarily) make this subject much more confusing and complicated than it actually is.
Kyle's answer is pretty good. I think the only additional clarification is that the closure is basically a snapshot of the stack at the point that the lambda function is created. Then when the function is re-executed the stack is restored to that state before executing the function. Thus as Kyle mentions, that hidden value (count) is available when the lambda function executes.
A closure is a function that can reference state in another function. For example, in Python, this uses the closure "inner":
def outer (a):
b = "variable in outer()"
def inner (c):
print a, b, c
return inner
# Now the return value from outer() can be saved for later
func = outer ("test")
func (1) # prints "test variable in outer() 1
To help facilitate understanding of closures it might be useful to examine how they might be implemented in a procedural language. This explanation will follow a simplistic implementation of closures in Scheme.
To start, I must introduce the concept of a namespace. When you enter a command into a Scheme interpreter, it must evaluate the various symbols in the expression and obtain their value. Example:
(define x 3)
(define y 4)
(+ x y) returns 7
The define expressions store the value 3 in the spot for x and the value 4 in the spot for y. Then when we call (+ x y), the interpreter looks up the values in the namespace and is able to perform the operation and return 7.
However, in Scheme there are expressions that allow you to temporarily override the value of a symbol. Here's an example:
(define x 3)
(define y 4)
(let ((x 5))
(+ x y)) returns 9
x returns 3
What the let keyword does is introduces a new namespace with x as the value 5. You will notice that it's still able to see that y is 4, making the sum returned to be 9. You can also see that once the expression has ended x is back to being 3. In this sense, x has been temporarily masked by the local value.
Procedural and object-oriented languages have a similar concept. Whenever you declare a variable in a function that has the same name as a global variable you get the same effect.
How would we implement this? A simple way is with a linked list - the head contains the new value and the tail contains the old namespace. When you need to look up a symbol, you start at the head and work your way down the tail.
Now let's skip to the implementation of first-class functions for the moment. More or less, a function is a set of instructions to execute when the function is called culminating in the return value. When we read in a function, we can store these instructions behind the scenes and run them when the function is called.
(define x 3)
(define (plus-x y)
(+ x y))
(let ((x 5))
(plus-x 4)) returns ?
We define x to be 3 and plus-x to be its parameter, y, plus the value of x. Finally we call plus-x in an environment where x has been masked by a new x, this one valued 5. If we merely store the operation, (+ x y), for the function plus-x, since we're in the context of x being 5 the result returned would be 9. This is what's called dynamic scoping.
However, Scheme, Common Lisp, and many other languages have what's called lexical scoping - in addition to storing the operation (+ x y) we also store the namespace at that particular point. That way, when we're looking up the values we can see that x, in this context, is really 3. This is a closure.
(define x 3)
(define (plus-x y)
(+ x y))
(let ((x 5))
(plus-x 4)) returns 7
In summary, we can use a linked list to store the state of the namespace at the time of function definition, allowing us to access variables from enclosing scopes, as well as providing us the ability to locally mask a variable without affecting the rest of the program.
Functions containing no free variables are called pure functions.
Functions containing one or more free variables are called closures.
var pure = function pure(x){
return x
// only own environment is used
}
var foo = "bar"
var closure = function closure(){
return foo
// foo is a free variable from the outer environment
}
src: https://leanpub.com/javascriptallongesix/read#leanpub-auto-if-functions-without-free-variables-are-pure-are-closures-impure
Here's a real world example of why Closures kick ass... This is straight out of my Javascript code. Let me illustrate.
Function.prototype.delay = function(ms /*[, arg...]*/) {
var fn = this,
args = Array.prototype.slice.call(arguments, 1);
return window.setTimeout(function() {
return fn.apply(fn, args);
}, ms);
};
And here's how you would use it:
var startPlayback = function(track) {
Player.play(track);
};
startPlayback(someTrack);
Now imagine you want the playback to start delayed, like for example 5 seconds later after this code snippet runs. Well that's easy with delay and it's closure:
startPlayback.delay(5000, someTrack);
// Keep going, do other things
When you call delay with 5000ms, the first snippet runs, and stores the passed in arguments in it's closure. Then 5 seconds later, when the setTimeout callback happens, the closure still maintains those variables, so it can call the original function with the original parameters.
This is a type of currying, or function decoration.
Without closures, you would have to somehow maintain those variables state outside the function, thus littering code outside the function with something that logically belongs inside it. Using closures can greatly improve the quality and readability of your code.
tl;dr
A closure is a function and its scope assigned to (or used as) a variable. Thus, the name closure: the scope and the function is enclosed and used just like any other entity.
In depth Wikipedia style explanation
According to Wikipedia, a closure is:
Techniques for implementing lexically scoped name binding in languages with first-class functions.
What does that mean? Lets look into some definitions.
I will explain closures and other related definitions by using this example:
function startAt(x) {
return function (y) {
return x + y;
}
}
var closure1 = startAt(1);
var closure2 = startAt(5);
console.log(closure1(3)); // 4 (x == 1, y == 3)
console.log(closure2(3)); // 8 (x == 5, y == 3)
First-class functions
Basically that means we can use functions just like any other entity. We can modify them, pass them as arguments, return them from functions or assign them for variables. Technically speaking, they are first-class citizens, hence the name: first-class functions.
In the example above, startAt returns an (anonymous) function which function get assigned to closure1 and closure2. So as you see JavaScript treats functions just like any other entities (first-class citizens).
Name binding
Name binding is about finding out what data a variable (identifier) references. The scope is really important here, as that is the thing that will determine how a binding is resolved.
In the example above:
In the inner anonymous function's scope, y is bound to 3.
In startAt's scope, x is bound to 1 or 5 (depending on the closure).
Inside the anonymous function's scope, x is not bound to any value, so it needs to be resolved in an upper (startAt's) scope.
Lexical scoping
As Wikipedia says, the scope:
Is the region of a computer program where the binding is valid: where the name can be used to refer to the entity.
There are two techniques:
Lexical (static) scoping: A variable's definition is resolved by searching its containing block or function, then if that fails searching the outer containing block, and so on.
Dynamic scoping: Calling function is searched, then the function which called that calling function, and so on, progressing up the call stack.
For more explanation, check out this question and take a look at Wikipedia.
In the example above, we can see that JavaScript is lexically scoped, because when x is resolved, the binding is searched in the upper (startAt's) scope, based on the source code (the anonymous function that looks for x is defined inside startAt) and not based on the call stack, the way (the scope where) the function was called.
Wrapping (closuring) up
In our example, when we call startAt, it will return a (first-class) function that will be assigned to closure1 and closure2 thus a closure is created, because the passed variables 1 and 5 will be saved within startAt's scope, that will be enclosed with the returned anonymous function. When we call this anonymous function via closure1 and closure2 with the same argument (3), the value of y will be found immediately (as that is the parameter of that function), but x is not bound in the scope of the anonymous function, so the resolution continues in the (lexically) upper function scope (that was saved in the closure) where x is found to be bound to either 1 or 5. Now we know everything for the summation so the result can be returned, then printed.
Now you should understand closures and how they behave, which is a fundamental part of JavaScript.
Currying
Oh, and you also learned what currying is about: you use functions (closures) to pass each argument of an operation instead of using one functions with multiple parameters.
Closure is a feature in JavaScript where a function has access to its own scope variables, access to the outer function variables and access to the global variables.
Closure has access to its outer function scope even after the outer function has returned. This means a closure can remember and access variables and arguments of its outer function even after the function has finished.
The inner function can access the variables defined in its own scope, the outer function’s scope, and the global scope. And the outer function can access the variable defined in its own scope and the global scope.
Example of Closure:
var globalValue = 5;
function functOuter() {
var outerFunctionValue = 10;
//Inner function has access to the outer function value
//and the global variables
function functInner() {
var innerFunctionValue = 5;
alert(globalValue + outerFunctionValue + innerFunctionValue);
}
functInner();
}
functOuter();
Output will be 20 which sum of its inner function own variable, outer function variable and global variable value.
In a normal situation, variables are bound by scoping rule: Local variables work only within the defined function. Closure is a way of breaking this rule temporarily for convenience.
def n_times(a_thing)
return lambda{|n| a_thing * n}
end
in the above code, lambda(|n| a_thing * n} is the closure because a_thing is referred by the lambda (an anonymous function creator).
Now, if you put the resulting anonymous function in a function variable.
foo = n_times(4)
foo will break the normal scoping rule and start using 4 internally.
foo.call(3)
returns 12.
In short, function pointer is just a pointer to a location in the program code base (like program counter). Whereas Closure = Function pointer + Stack frame.
.
Closures provide JavaScript with state.
State in programming simply means remembering things.
Example
var a = 0;
a = a + 1; // => 1
a = a + 1; // => 2
a = a + 1; // => 3
In the case above, state is stored in the variable "a". We follow by adding 1 to "a" several times. We can only do that because we are able to "remember" the value. The state holder, "a", holds that value in memory.
Often, in programming languages, you want to keep track of things, remember information and access it at a later time.
This, in other languages, is commonly accomplished through the use of classes. A class, just like variables, keeps track of its state. And instances of that class, in turns, also have state within them. State simply means information that you can store and retrieve later.
Example
class Bread {
constructor (weight) {
this.weight = weight;
}
render () {
return `My weight is ${this.weight}!`;
}
}
How can we access "weight" from within the "render" method? Well, thanks to state. Each instance of the class Bread can render its own weight by reading it from the "state", a place in memory where we could store that information.
Now, JavaScript is a very unique language which historically does not have classes (it now does, but under the hood there's only functions and variables) so Closures provide a way for JavaScript to remember things and access them later.
Example
var n = 0;
var count = function () {
n = n + 1;
return n;
};
count(); // # 1
count(); // # 2
count(); // # 3
The example above achieved the goal of "keeping state" with a variable. This is great! However, this has the disadvantage that the variable (the "state" holder) is now exposed. We can do better. We can use Closures.
Example
var countGenerator = function () {
var n = 0;
var count = function () {
n = n + 1;
return n;
};
return count;
};
var count = countGenerator();
count(); // # 1
count(); // # 2
count(); // # 3
This is fantastic.
Now our "count" function can count. It is only able to do so because it can "hold" state. The state in this case is the variable "n". This variable is now closed. Closed in time and space. In time because you won't ever be able to recover it, change it, assign it a value or interact directly with it. In space because it's geographically nested within the "countGenerator" function.
Why is this fantastic? Because without involving any other sophisticated and complicated tool (e.g. classes, methods, instances, etc) we are able to
1. conceal
2. control from a distance
We conceal the state, the variable "n", which makes it a private variable!
We also have created an API that can control this variable in a pre-defined way. In particular, we can call the API like so "count()" and that adds 1 to "n" from a "distance". In no way, shape or form anyone will ever be able to access "n" except through the API.
JavaScript is truly amazing in its simplicity.
Closures are a big part of why this is.
Here is another real life example, and using a scripting language popular in games - Lua. I needed to slightly change the way a library function worked to avoid a problem with stdin not being available.
local old_dofile = dofile
function dofile( filename )
if filename == nil then
error( 'Can not use default of stdin.' )
end
old_dofile( filename )
end
The value of old_dofile disappears when this block of code finishes it's scope (because it's local), however the value has been enclosed in a closure, so the new redefined dofile function CAN access it, or rather a copy stored along with the function as an 'upvalue'.
From Lua.org:
When a function is written enclosed in another function, it has full access to local variables from the enclosing function; this feature is called lexical scoping. Although that may sound obvious, it is not. Lexical scoping, plus first-class functions, is a powerful concept in a programming language, but few languages support that concept.
If you are from the Java world, you can compare a closure with a member function of a class. Look at this example
var f=function(){
var a=7;
var g=function(){
return a;
}
return g;
}
The function g is a closure: g closes a in. So g can be compared with a member function, a can be compared with a class field, and the function f with a class.
Closures
Whenever we have a function defined inside another function, the inner function has access to the variables declared
in the outer function. Closures are best explained with examples.
In Listing 2-18, you can see that the inner function has access to a variable (variableInOuterFunction) from the
outer scope. The variables in the outer function have been closed by (or bound in) the inner function. Hence the term
closure. The concept in itself is simple enough and fairly intuitive.
Listing 2-18:
function outerFunction(arg) {
var variableInOuterFunction = arg;
function bar() {
console.log(variableInOuterFunction); // Access a variable from the outer scope
}
// Call the local function to demonstrate that it has access to arg
bar();
}
outerFunction('hello closure!'); // logs hello closure!
source: http://index-of.es/Varios/Basarat%20Ali%20Syed%20(auth.)-Beginning%20Node.js-Apress%20(2014).pdf
Please have a look below code to understand closure in more deep:
for(var i=0; i< 5; i++){
setTimeout(function(){
console.log(i);
}, 1000);
}
Here what will be output? 0,1,2,3,4 not that will be 5,5,5,5,5 because of closure
So how it will solve? Answer is below:
for(var i=0; i< 5; i++){
(function(j){ //using IIFE
setTimeout(function(){
console.log(j);
},1000);
})(i);
}
Let me simple explain, when a function created nothing happen until it called so for loop in 1st code called 5 times but not called immediately so when it called i.e after 1 second and also this is asynchronous so before this for loop finished and store value 5 in var i and finally execute setTimeout function five time and print 5,5,5,5,5
Here how it solve using IIFE i.e Immediate Invoking Function Expression
(function(j){ //i is passed here
setTimeout(function(){
console.log(j);
},1000);
})(i); //look here it called immediate that is store i=0 for 1st loop, i=1 for 2nd loop, and so on and print 0,1,2,3,4
For more, please understand execution context to understand closure.
There is one more solution to solve this using let (ES6 feature) but under the hood above function is worked
for(let i=0; i< 5; i++){
setTimeout(function(){
console.log(i);
},1000);
}
Output: 0,1,2,3,4
=> More explanation:
In memory, when for loop execute picture make like below:
Loop 1)
setTimeout(function(){
console.log(i);
},1000);
Loop 2)
setTimeout(function(){
console.log(i);
},1000);
Loop 3)
setTimeout(function(){
console.log(i);
},1000);
Loop 4)
setTimeout(function(){
console.log(i);
},1000);
Loop 5)
setTimeout(function(){
console.log(i);
},1000);
Here i is not executed and then after complete loop, var i stored value 5 in memory but it's scope is always visible in it's children function so when function execute inside setTimeout out five time it prints 5,5,5,5,5
so to resolve this use IIFE as explain above.
Currying : It allows you to partially evaluate a function by only passing in a subset of its arguments. Consider this:
function multiply (x, y) {
return x * y;
}
const double = multiply.bind(null, 2);
const eight = double(4);
eight == 8;
Closure: A closure is nothing more than accessing a variable outside of a function's scope. It is important to remember that a function inside a function or a nested function isn't a closure. Closures are always used when need to access the variables outside the function scope.
function apple(x){
function google(y,z) {
console.log(x*y);
}
google(7,2);
}
apple(3);
// the answer here will be 21
Closure is very easy. We can consider it as follows :
Closure = function + its lexical environment
Consider the following function:
function init() {
var name = “Mozilla”;
}
What will be the closure in the above case ?
Function init() and variables in its lexical environment ie name.
Closure = init() + name
Consider another function :
function init() {
var name = “Mozilla”;
function displayName(){
alert(name);
}
displayName();
}
What will be the closures here ?
Inner function can access variables of outer function. displayName() can access the variable name declared in the parent function, init(). However, the same local variables in displayName() will be used if they exists.
Closure 1 : init function + ( name variable + displayName() function) --> lexical scope
Closure 2 : displayName function + ( name variable ) --> lexical scope
A simple example in Groovy for your reference:
def outer() {
def x = 1
return { -> println(x)} // inner
}
def innerObj = outer()
innerObj() // prints 1
Here is an example illustrating a closure in the Scheme programming language.
First we define a function defining a local variable, not visible outside the function.
; Function using a local variable
(define (function)
(define a 1)
(display a) ; prints 1, when calling (function)
)
(function) ; prints 1
(display a) ; fails: a undefined
Here is the same example, but now the function uses a global variable, defined outside the function.
; Function using a global variable
(define b 2)
(define (function)
(display b) ; prints 2, when calling (function)
)
(function) ; prints 2
(display 2) ; prints 2
And finally, here is an example of a function carrying its own closure:
; Function with closure
(define (outer)
(define c 3)
(define (inner)
(display c))
inner ; outer function returns the inner function as result
)
(define function (outer))
(function) ; prints 3

Resources