How to conceptualize a lexical scope tree when you can have hoisted nested functions? - scope

I am working on a compiler in TypeScript and thinking a lot about lexical scope. In particular I'm wondering about how you handle the situation where you have hoisted functions, where variables can be undefined at one point, and then defined at another point. For example:
function a() {
let d = 10
b()
return b
let g = 40
function b() {
c()
let f = 30
return c
function c() {
console.log(d, e, f, g)
}
}
let e = 20
}
const x = a()() // returns b, returns c
x() // log the variables
Here, what is the "lexical scope" inside the function c?
Is it all the variables it could possibly/potentially have access to (at some point) during possible code evaluation? (d, e, f, g)
Is it what it only will eventually be defined within its runtime context? (d, f)
Is it what won't be undefined and throw an error? (d)
Is it every combination of possible parents all at once (like a cartesian product sort of thing, times however many parents in the tree)?
etc.
At first, for a while (for many years), I thought of lexical scope as a simple tree. You had higher scopes and nested scopes, and each nested scope introduced new variables. Nice and clean, easy-peasy. But this, this throws it for a loop. Now it's like, focusing on c, there are steps of evaluation inside b, and at each step, a possible different parent scope may exist. Then a might have a suite of parent scopes too. So it is like a natural flower/tree that blossoms upward (which is hard to imagine in programming). There are more and more possible parents. What I'm thinking is, the lexical scope is the combination of every combination of parents on upward. But then how do you use this scope in a compiler?
Now I am confused. What am I supposed to use the lexical scope for in a compiler if I can't tell for a nested function what 1 scope definition it is? I assumed each nested function has 1 scope, but no, it's parents are vast and combinatory. You can only really tell what the scope is when it is bound ("binding", as opposed to "scope"). That is, at the specific step in code evaluation, what the value of the scope is.
So how do you use this information in a compiler? I can tell if a variable is in scope only seemingly if I evaluate/simulate the code running itself. Basically, how do I use this lexical scope in a compiler now with this confusion?
I was going to use it as the source of truth for what variables were defined in a nested lexical scope block. But now I can't, because I need to know at each step what the values of the variables are before I can know what the scope is. Or am I missing something?
Thinking of trying something like this:
type SiteContainerScopeType = {
like: Site.ContainerScopeType
parent?: SiteContainerScopeType
children: Array<SiteContainerStepScopeType>
declarations: Record<string, SitePropertyDeclarationType>
}
type SiteContainerStepScopeType = {
like: Site.ContainerStepScope
previous: SiteContainerStepScopeType
context: SiteContainerScopeType
declarations: Record<string, SitePropertyDeclarationType>
}

If I understand correctly the semantics described in Understanding Hoisting in JavaScript, the code can be reorganized as follows, ordering first declarations, then variable initialization and finally the rest of the expressions.
function a() {
// DECLARATIONS
let d
let g
let e
function b() {
let f
function c() {
console.log(d, e, f, g)
}
f = 30
c()
return c
}
// INITIALIZATION
e = 20
d = 10
g = 40
// EXPRESSIONS
b()
return b
}
When doing this, we find a more usual structure of having variables declared before being initialized and used.

Related

Understanding recurive let expression in lambda calculus with Haskell, OCaml and nix language

I'm trying to understand how recursive set operate internally by comparing similar feature in another functional programming languages and concepts.
I can find it in wiki. In that, I need to know Y combinator, fixed point. I can get it briefly in wiki.
Then, now I start to apply this in Haskell.
Haskell
It is easy. But I want to know behind the scenes.
*Main> let x = y; y = 10; in x
10
When you write a = f b in a lazy functional language like Haskell or Nix, the meaning is stronger than just assignment. a and f b will be the same thing. This is usually called a binding.
I'll focus on a Nix example, because you're asking about recursive sets specifically.
A simple attribute set
Let's look at the initialization of an attribute set first. When the Nix interpreter is asked to evaluate this file
{ a = 1 + 1; b = true; }
it parses it and returns a data structure like this
{ a = <thunk 1>; b = <thunk 2>; }
where a thunk is a reference to the relevant syntax tree node and a reference to the "environment", which behaves like a dictionary from identifiers to their values, although implemented more efficiently.
Perhaps the reason we're evaluating this file is because you requested nix-build, which will not just ask for the value of a file, but also traverse the attribute set when it sees that it is one. So nix-build will ask for the value of a, which will be computed from its thunk. When the computation is complete, the memory that held the thunk is assigned the actual value, type = tInt, value.integer = 2.
A recursive attribute set
Nix has a special syntax that combines the functionality of attribute set construction syntax ({ }) and let-binding syntax. This is avoids some repetition when you're constructing attribute sets with some shared values.
For example
let b = 1 + 1;
in { b = b; a = b + 5; }
can be expressed as
rec { b = 1 + 1; a = b + 5; }
Evaluation works in a similar manner.
At first the evaluator returns a representation of the attribute set with all thunks, but this time the thunks reference an new environment that includes all the attributes, on top of the existing lexical scope.
Note that all these representations can be constructed while performing a minimal amount of work.
nix-build traverses attrsets in alphabetic order, so it will evaluate a first. It's a thunk that references the a + syntax node and an environment with b in it. Evaluating this requires evaluating the b syntax node (an ExprVar), which references the environment, where we find the 1 + 1 thunk, which is changed to a tInt of 2 as before.
As you can see, this process of creating thunks but only evaluating them when needed is indeed lazy and allows us to have various language constructs with their own scoping rules.
Haskell implementations usually follow a similar pattern, but may compile the code rather than interpret a syntax tree, and resolve all variable references to constant memory offsets completely. Nix tries to do this to some degree, but it must be able to fall back on strings because of the inadvisable with keyword that makes the scope dynamic.
I guess several things by myself.
In eagar evaluation language, I must declare before use it. So the order of declaration is simple.
int x = 10;
int y = x;
Just for Nix language
In wiki, there isn't any concept comparision with Haskell though let ... in is compared with Haskell.
lexical scope
all variables are lexically scoped.
mutual recursion
https://en.wikipedia.org/wiki/Let_expression#Mutually_recursive_let_expression

Variable scope witihin requirejs modules [duplicate]

What is the scope of variables in javascript? Do they have the same scope inside as opposed to outside a function? Or does it even matter? Also, where are the variables stored if they are defined globally?
TLDR
JavaScript has lexical (also called static) scoping and closures. This means you can tell the scope of an identifier by looking at the source code.
The four scopes are:
Global - visible by everything
Function - visible within a function (and its sub-functions and blocks)
Block - visible within a block (and its sub-blocks)
Module - visible within a module
Outside of the special cases of global and module scope, variables are declared using var (function scope), let (block scope), and const (block scope). Most other forms of identifier declaration have block scope in strict mode.
Overview
Scope is the region of the codebase over which an identifier is valid.
A lexical environment is a mapping between identifier names and the values associated with them.
Scope is formed of a linked nesting of lexical environments, with each level in the nesting corresponding to a lexical environment of an ancestor execution context.
These linked lexical environments form a scope "chain". Identifier resolution is the process of searching along this chain for a matching identifier.
Identifier resolution only occurs in one direction: outwards. In this way, outer lexical environments cannot "see" into inner lexical environments.
There are three pertinent factors in deciding the scope of an identifier in JavaScript:
How an identifier was declared
Where an identifier was declared
Whether you are in strict mode or non-strict mode
Some of the ways identifiers can be declared:
var, let and const
Function parameters
Catch block parameter
Function declarations
Named function expressions
Implicitly defined properties on the global object (i.e., missing out var in non-strict mode)
import statements
eval
Some of the locations identifiers can be declared:
Global context
Function body
Ordinary block
The top of a control structure (e.g., loop, if, while, etc.)
Control structure body
Modules
Declaration Styles
var
Identifiers declared using var have function scope, apart from when they are declared directly in the global context, in which case they are added as properties on the global object and have global scope. There are separate rules for their use in eval functions.
let and const
Identifiers declared using let and const have block scope, apart from when they are declared directly in the global context, in which case they have global scope.
Note: let, const and var are all hoisted. This means that their logical position of definition is the top of their enclosing scope (block or function). However, variables declared using let and const cannot be read or assigned to until control has passed the point of declaration in the source code. The interim period is known as the temporal dead zone.
function f() {
function g() {
console.log(x)
}
let x = 1
g()
}
f() // 1 because x is hoisted even though declared with `let`!
Function parameter names
Function parameter names are scoped to the function body. Note that there is a slight complexity to this. Functions declared as default arguments close over the parameter list, and not the body of the function.
Function declarations
Function declarations have block scope in strict mode and function scope in non-strict mode. Note: non-strict mode is a complicated set of emergent rules based on the quirky historical implementations of different browsers.
Named function expressions
Named function expressions are scoped to themselves (e.g., for the purpose of recursion).
Implicitly defined properties on the global object
In non-strict mode, implicitly defined properties on the global object have global scope, because the global object sits at the top of the scope chain. In strict mode, these are not permitted.
eval
In eval strings, variables declared using var will be placed in the current scope, or, if eval is used indirectly, as properties on the global object.
Examples
The following will throw a ReferenceError because the namesx, y, and z have no meaning outside of the function f.
function f() {
var x = 1
let y = 1
const z = 1
}
console.log(typeof x) // undefined (because var has function scope!)
console.log(typeof y) // undefined (because the body of the function is a block)
console.log(typeof z) // undefined (because the body of the function is a block)
The following will throw a ReferenceError for y and z, but not for x, because the visibility of x is not constrained by the block. Blocks that define the bodies of control structures like if, for, and while, behave similarly.
{
var x = 1
let y = 1
const z = 1
}
console.log(x) // 1
console.log(typeof y) // undefined because `y` has block scope
console.log(typeof z) // undefined because `z` has block scope
In the following, x is visible outside of the loop because var has function scope:
for(var x = 0; x < 5; ++x) {}
console.log(x) // 5 (note this is outside the loop!)
...because of this behavior, you need to be careful about closing over variables declared using var in loops. There is only one instance of variable x declared here, and it sits logically outside of the loop.
The following prints 5, five times, and then prints 5 a sixth time for the console.log outside the loop:
for(var x = 0; x < 5; ++x) {
setTimeout(() => console.log(x)) // closes over the `x` which is logically positioned at the top of the enclosing scope, above the loop
}
console.log(x) // note: visible outside the loop
The following prints undefined because x is block-scoped. The callbacks are run one by one asynchronously. New behavior for let variables means that each anonymous function closed over a different variable named x (unlike it would have done with var), and so integers 0 through 4 are printed.:
for(let x = 0; x < 5; ++x) {
setTimeout(() => console.log(x)) // `let` declarations are re-declared on a per-iteration basis, so the closures capture different variables
}
console.log(typeof x) // undefined
The following will NOT throw a ReferenceError because the visibility of x is not constrained by the block; it will, however, print undefined because the variable has not been initialised (because of the if statement).
if(false) {
var x = 1
}
console.log(x) // here, `x` has been declared, but not initialised
A variable declared at the top of a for loop using let is scoped to the body of the loop:
for(let x = 0; x < 10; ++x) {}
console.log(typeof x) // undefined, because `x` is block-scoped
The following will throw a ReferenceError because the visibility of x is constrained by the block:
if(false) {
let x = 1
}
console.log(typeof x) // undefined, because `x` is block-scoped
Variables declared using var, let or const are all scoped to modules:
// module1.js
var x = 0
export function f() {}
//module2.js
import f from 'module1.js'
console.log(x) // throws ReferenceError
The following will declare a property on the global object because variables declared using var within the global context are added as properties to the global object:
var x = 1
console.log(window.hasOwnProperty('x')) // true
let and const in the global context do not add properties to the global object, but still have global scope:
let x = 1
console.log(window.hasOwnProperty('x')) // false
Function parameters can be considered to be declared in the function body:
function f(x) {}
console.log(typeof x) // undefined, because `x` is scoped to the function
Catch block parameters are scoped to the catch-block body:
try {} catch(e) {}
console.log(typeof e) // undefined, because `e` is scoped to the catch block
Named function expressions are scoped only to the expression itself:
(function foo() { console.log(foo) })()
console.log(typeof foo) // undefined, because `foo` is scoped to its own expression
In non-strict mode, implicitly defined properties on the global object are globally scoped. In strict mode, you get an error.
x = 1 // implicitly defined property on the global object (no "var"!)
console.log(x) // 1
console.log(window.hasOwnProperty('x')) // true
In non-strict mode, function declarations have function scope. In strict mode, they have block scope.
'use strict'
{
function foo() {}
}
console.log(typeof foo) // undefined, because `foo` is block-scoped
How it works under the hood
Scope is defined as the lexical region of code over which an identifier is valid.
In JavaScript, every function-object has a hidden [[Environment]] reference that is a reference to the lexical environment of the execution context (stack frame) within which it was created.
When you invoke a function, the hidden [[Call]] method is called. This method creates a new execution context and establishes a link between the new execution context and the lexical environment of the function-object. It does this by copying the [[Environment]] value on the function-object, into an outer reference field on the lexical environment of the new execution context.
Note that this link between the new execution context and the lexical environment of the function object is called a closure.
Thus, in JavaScript, scope is implemented via lexical environments linked together in a "chain" by outer references. This chain of lexical environments is called the scope chain, and identifier resolution occurs by searching up the chain for a matching identifier.
Find out more.
Javascript uses scope chains to establish the scope for a given function. There is typically one global scope, and each function defined has its own nested scope. Any function defined within another function has a local scope which is linked to the outer function. It's always the position in the source that defines the scope.
An element in the scope chain is basically a Map with a pointer to its parent scope.
When resolving a variable, javascript starts at the innermost scope and searches outwards.
Variables declared globally have a global scope. Variables declared within a function are scoped to that function, and shadow global variables of the same name.
(I'm sure there are many subtleties that real JavaScript programmers will be able to point out in other answers. In particular I came across this page about what exactly this means at any time. Hopefully this more introductory link is enough to get you started though.)
Old school JavaScript
Traditionally, JavaScript really only has two types of scope :
Global Scope : Variables are known throughout the application, from the start of the application (*)
Functional Scope : Variables are known within the function they are declared in, from the start of the function (*)
I will not elaborate on this, since there are already many other answers explaining the difference.
Modern JavaScript
The most recent JavaScript specs now also allow a third scope :
Block Scope : Identifiers are "known" from the top of the scope they are declared within, but they cannot be assigned to or dereferenced (read) until after the line of their declaration. This interim period is called the "temporal dead zone."
How do I create block scope variables?
Traditionally, you create your variables like this :
var myVariable = "Some text";
Block scope variables are created like this :
let myVariable = "Some text";
So what is the difference between functional scope and block scope?
To understand the difference between functional scope and block scope, consider the following code :
// i IS NOT known here
// j IS NOT known here
// k IS known here, but undefined
// l IS NOT known here
function loop(arr) {
// i IS known here, but undefined
// j IS NOT known here
// k IS known here, but has a value only the second time loop is called
// l IS NOT known here
for( var i = 0; i < arr.length; i++ ) {
// i IS known here, and has a value
// j IS NOT known here
// k IS known here, but has a value only the second time loop is called
// l IS NOT known here
};
// i IS known here, and has a value
// j IS NOT known here
// k IS known here, but has a value only the second time loop is called
// l IS NOT known here
for( let j = 0; j < arr.length; j++ ) {
// i IS known here, and has a value
// j IS known here, and has a value
// k IS known here, but has a value only the second time loop is called
// l IS NOT known here
};
// i IS known here, and has a value
// j IS NOT known here
// k IS known here, but has a value only the second time loop is called
// l IS NOT known here
}
loop([1,2,3,4]);
for( var k = 0; k < arr.length; k++ ) {
// i IS NOT known here
// j IS NOT known here
// k IS known here, and has a value
// l IS NOT known here
};
for( let l = 0; l < arr.length; l++ ) {
// i IS NOT known here
// j IS NOT known here
// k IS known here, and has a value
// l IS known here, and has a value
};
loop([1,2,3,4]);
// i IS NOT known here
// j IS NOT known here
// k IS known here, and has a value
// l IS NOT known here
Here, we can see that our variable j is only known in the first for loop, but not before and after. Yet, our variable i is known in the entire function.
Also, consider that block scoped variables are not known before they are declared because they are not hoisted. You're also not allowed to redeclare the same block scoped variable within the same block. This makes block scoped variables less error prone than globally or functionally scoped variables, which are hoisted and which do not produce any errors in case of multiple declarations.
Is it safe to use block scope variables today?
Whether or not it is safe to use today, depends on your environment :
If you're writing server-side JavaScript code (Node.js), you can safely use the let statement.
If you're writing client-side JavaScript code and use a browser based transpiler (like Traceur or babel-standalone), you can safely use the let statement, however your code is likely to be anything but optimal with respect to performance.
If you're writing client-side JavaScript code and use a Node based transpiler (like the traceur shell script or Babel), you can safely use the let statement. And because your browser will only know about the transpiled code, performance drawbacks should be limited.
If you're writing client-side JavaScript code and don't use a transpiler, you need to consider browser support.
These are some browsers that don't support let at all :
Internet explorer 10 and below
Firefox 43 and below
Safari 9 and below
Android browser 4 and below
Opera 27 and below
Chome 40 and below
ANY version of Opera Mini & Blackberry Browser
How to keep track of browser support
For an up-to-date overview of which browsers support the let statement at the time of your reading this answer, see this Can I Use page.
(*) Globally and functionally scoped variables can be initialized and used before they are declared because JavaScript variables are hoisted. This means that declarations are always much to the top of the scope.
Here's an example:
<script>
var globalVariable = 7; //==window.globalVariable
function aGlobal( param ) { //==window.aGlobal();
//param is only accessible in this function
var scopedToFunction = {
//can't be accessed outside of this function
nested : 3 //accessible by: scopedToFunction.nested
};
anotherGlobal = {
//global because there's no `var`
};
}
</script>
You'll want to investigate closures, and how to use them to make private members.
The key, as I understand it, is that Javascript has function level scoping vs the more common C block scoping.
Here is a good article on the subject.
In "Javascript 1.7" (Mozilla's extension to Javascript) one can also declare block-scope variables with let statement:
var a = 4;
let (a = 3) {
alert(a); // 3
}
alert(a); // 4
The idea of scoping in JavaScript when originally designed by Brendan Eich came from the HyperCard scripting language HyperTalk.
In this language, the displays were done similar to a stack of index cards. There was a master card referred to as the background. It was transparent and can be seen as the bottom card. Any content on this base card was shared with cards placed on top of it. Each card placed on top had its own content which took precedence over the previous card, but still had access to the prior cards if desired.
This is exactly how the JavaScript scoping system is designed. It just has different names. The cards in JavaScript are known as Execution ContextsECMA. Each one of these contexts contains three main parts. A variable environment, a lexical environment, and a this binding. Going back to the cards reference, the lexical environment contains all of the content from prior cards lower in the stack. The current context is at the top of the stack and any content declared there will be stored in the variable environment. The variable environment will take precedence in the case of naming collisions.
The this binding will point to the containing object. Sometimes scopes or execution contexts change without the containing object changing, such as in a declared function where the containing object may be window or a constructor function.
These execution contexts are created any time control is transferred. Control is transferred when code begins to execute, and this is primarily done from function execution.
So that is the technical explanation. In practice, it is important to remember that in JavaScript
Scopes are technically "Execution Contexts"
Contexts form a stack of environments where variables are stored
The top of the stack takes precedence (the bottom being the global context)
Each function creates an execution context (but not always a new this binding)
Applying this to one of the previous examples (5. "Closure") on this page, it is possible to follow the stack of execution contexts. In this example there are three contexts in the stack. They are defined by the outer context, the context in the immediately invoked function called by var six, and the context in the returned function inside of var six's immediately invoked function.
i) The outer context. It has a variable environment of a = 1
ii) The IIFE context, it has a lexical environment of a = 1, but a variable environment of a = 6 which takes precedence in the stack
iii) The returned function context, it has a lexical environment of a = 6 and that is the value referenced in the alert when called.
1) There is a global scope, a function scope, and the with and catch scopes. There is no 'block' level scope in general for variable's -- the with and the catch statements add names to their blocks.
2) Scopes are nested by functions all the way to the global scope.
3) Properties are resolved by going through the prototype chain. The with statement brings object property names into the lexical scope defined by the with block.
EDIT: ECMAAScript 6 (Harmony) is spec'ed to support let, and I know chrome allows a 'harmony' flag, so perhaps it does support it..
Let would be a support for block level scoping, but you have to use the keyword to make it happen.
EDIT: Based on Benjamin's pointing out of the with and catch statements in the comments, I've edited the post, and added more. Both the with and the catch statements introduce variables into their respective blocks, and that is a block scope. These variables are aliased to the properties of the objects passed into them.
//chrome (v8)
var a = { 'test1':'test1val' }
test1 // error not defined
with (a) { var test1 = 'replaced' }
test1 // undefined
a // a.test1 = 'replaced'
EDIT: Clarifying example:
test1 is scoped to the with block, but is aliased to a.test1. 'Var test1' creates a new variable test1 in the upper lexical context (function, or global), unless it is a property of a -- which it is.
Yikes! Be careful using 'with' -- just like var is a noop if the variable is already defined in the function, it is also a noop with respect to names imported from the object! A little heads up on the name already being defined would make this much safer. I personally will never use with because of this.
Inline handlers
A very common issue not described yet that front-end coders often run into is the scope that is visible to an inline event handler in the HTML - for example, with
<button onclick="foo()"></button>
The scope of the variables that an on* attribute can reference must be either:
global (working inline handlers almost always reference global variables)
a property of the document (eg, querySelector as a standalone variable will point to document.querySelector; rare)
a property of the element the handler is attached to (like above; rare)
Otherwise, you'll get a ReferenceError when the handler is invoked. So, for example, if the inline handler references a function which is defined inside window.onload or $(function() {, the reference will fail, because the inline handler may only reference variables in the global scope, and the function is not global:
window.addEventListener('DOMContentLoaded', () => {
function foo() {
console.log('foo running');
}
});
<button onclick="foo()">click</button>
Properties of the document and properties of the element the handler is attached to may also be referenced as standalone variables inside inline handlers because inline handlers are invoked inside of two with blocks, one for the document, one for the element. The scope chain of variables inside these handlers is extremely unintuitive, and a working event handler will probably require a function to be global (and unnecessary global pollution should probably be avoided).
Since the scope chain inside inline handlers is so weird, and since inline handlers require global pollution to work, and since inline handlers sometimes require ugly string escaping when passing arguments, it's probably easier to avoid them. Instead, attach event handlers using Javascript (like with addEventListener), rather than with HTML markup.
function foo() {
console.log('foo running');
}
document.querySelector('.my-button').addEventListener('click', foo);
<button class="my-button">click</button>
Modules (<script type="module">)
On a different note, unlike normal <script> tags, which run on the top level, code inside ES6 modules runs in its own private scope. A variable defined at the top of a normal <script> tag is global, so you can reference it in other <script> tags, like this:
<script>
const foo = 'foo';
</script>
<script>
console.log(foo);
</script>
But the top level of an ES6 module is not global. A variable declared at the top of an ES6 module will only be visible inside that module, unless the variable is explicitly exported, or unless it's assigned to a property of the global object.
<script type="module">
const foo = 'foo';
</script>
<script>
// Can't access foo here, because the other script is a module
console.log(typeof foo);
</script>
The top level of an ES6 module is similar to that of the inside of an IIFE on the top level in a normal <script>. The module can reference any variables which are global, and nothing can reference anything inside the module unless the module is explicitly designed for it.
I found that many people new to JavaScript have trouble understanding that inheritance is available by default in the language and that function scope is the only scope, so far. I provided an extension to a beautifier I wrote at the end of last year called JSPretty. The feature colors function scope in the code and always associates a color to all variables declared in that scope. Closure is visually demonstrated when a variable with a color from one scope is used in a different scope.
Try the feature at:
http://prettydiff.com/jspretty.xhtml?c=white&jsscope
See a demo at:
http://prettydiff.com/jspretty.xhtml?c=white&jsscope&s=http://prettydiff.com/lib/markup_beauty.js
View the code at:
http://prettydiff.com/lib/jspretty.js
https://github.com/austincheney/Pretty-Diff/blob/master/lib/jspretty.js
Currently the feature offers support for a depth of 16 nested functions, but currently does not color global variables.
JavaScript have only two type of scope :
Global Scope : Global is nothing but a window level scope.Here, variable present throughout the application.
Functional Scope : Variable declared within a function with var keyword has functional scope.
Whenever a function is called, a variable scope object is created (and included in scope chain) which is followed by variables in JavaScript.
a = "global";
function outer(){
b = "local";
console.log(a+b); //"globallocal"
}
outer();
Scope chain -->
Window level - a and outer function are at top level in scope chain.
when outer function called a new variable scope object(and included in scope chain) added with variable b inside it.
Now when a variable a required it first searches for nearest variable scope and if variable is not there than it move's to next object of variable scope chain.which is in this case is window level.
run the code. hope this will give an idea about scoping
Name = 'global data';
document.Name = 'current document data';
(function(window,document){
var Name = 'local data';
var myObj = {
Name: 'object data',
f: function(){
alert(this.Name);
}
};
myObj.newFun = function(){
alert(this.Name);
}
function testFun(){
alert("Window Scope : " + window.Name +
"\nLocal Scope : " + Name +
"\nObject Scope : " + this.Name +
"\nCurrent document Scope : " + document.Name
);
}
testFun.call(myObj);
})(window,document);
Global Scope :
Global variables are exactly like global stars (Jackie Chan, Nelson Mandela). You can access them (get or set the value), from any part of your application. Global functions are like global events (New Year, Christmas). You can execute (call) them from any part of your application.
//global variable
var a = 2;
//global function
function b(){
console.log(a); //access global variable
}
Local Scope :
If you are in the USA, you may know Kim Kardashian, infamous celebrity ( she somehow manages to make the tabloids). But people outside of the USA will not recognize her. She is a local star, bound to her territory.
Local variables are like local stars. You can only access them (get or set the value) inside the scope. A local function is like local events - you can execute only (celebrate) inside that scope. If you want to access them from outside of the scope, you will get a reference error
function b(){
var d = 21; //local variable
console.log(d);
function dog(){ console.log(a); }
dog(); //execute local function
}
console.log(d); //ReferenceError: dddddd is not defined
Check this article for in-depth understanding of scope
Just to add to the other answers, scope is a look-up list of all the declared identifiers (variables), and enforces a strict set of rules as to how these are accessible to currently executing code. This look-up may be for the purposes of assigning to the variable, which is an LHS (lefthand-side) reference, or it may be for the purposes of retrieving its value, which is an RHS (righthand-side) reference. These look-ups are what the JavaScript engine is doing internally when it's compiling and executing the code.
So from this perspective, I think that a picture would help that I found in the Scopes and Closures ebook by Kyle Simpson:
Quoting from his ebook:
The building represents our program’s nested scope ruleset. The first
floor of the building represents your currently executing scope,
wherever you are. The top level of the building is the global scope.
You resolve LHS and RHS references by looking on your current floor,
and if you don’t find it, taking the elevator to the next floor,
looking there, then the next, and so on. Once you get to the top floor
(the global scope), you either find what you’re looking for, or you
don’t. But you have to stop regardless.
One thing of note that is worth mentioning, "Scope look-up stops once it finds the first match".
This idea of "scope levels" explains why "this" can be changed with a newly created scope, if it's being looked up in a nested function.
Here is a link that goes into all these details, Everything you wanted to know about javascript scope
There are ALMOST only two types of JavaScript scopes:
the scope of each var declaration is associated with the most immediately enclosing function
if there is no enclosing function for a var declaration, it is global scope
So, any blocks other than functions do not create a new scope. That explains why for-loops overwrite outer scoped variables:
var i = 10, v = 10;
for (var i = 0; i < 5; i++) { var v = 5; }
console.log(i, v);
// output 5 5
Using functions instead:
var i = 10, v = 10;
$.each([0, 1, 2, 3, 4], function(i) { var v = 5; });
console.log(i,v);
// output 10 10
In the first example, there was no block scope, so the initially declared variables were overwritten. In the second example, there was a new scope due to the function, so the initially declared variables were SHADOWED, and not overwritten.
That's almost all you need to know in terms of JavaScript scoping, except:
try/catch introduce new scope ONLY for the exception variable itself, other variables do not have new scope
with-clause apparently is another exception, but using with-clause it highly discouraged (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with)
So you can see JavaScript scoping is actually extremely simple, albeit not always intuitive. A few things to be aware of:
var declarations are hoisted to the top of the scope. This means no matter where the var declaration happens, to the compiler it is as if the var itself happens at the top
multiple var declarations within the same scope are combined
So this code:
var i = 1;
function abc() {
i = 2;
var i = 3;
}
console.log(i); // outputs 1
is equivalent to:
var i = 1;
function abc() {
var i; // var declaration moved to the top of the scope
i = 2;
i = 3; // the assignment stays where it is
}
console.log(i);
This may seem counter intuitive, but it makes sense from the perspective of a imperative language designer.
Modern Js, ES6+, 'const' and 'let'
You should be using block scoping for every variable you create, just like most other major languages. var is obsolete. This makes your code safer and more maintainable.
const should be used for 95% of cases. It makes it so the variable reference can't change. Array, object, and DOM node properties can change and should likely be const.
let should be be used for any variable expecting to be reassigned. This includes within a for loop. If you ever change value beyond initialization, use let.
Block scope means that the variable will only be available within the brackets in which it is declared. This extends to internal scopes, including anonymous functions created within your scope.
Try this curious example. In the example below if a were a numeric initialized at 0, you'd see 0 and then 1. Except a is an object and javascript will pass f1 a pointer of a rather than a copy of it. The result is that you get the same alert both times.
var a = new Date();
function f1(b)
{
b.setDate(b.getDate()+1);
alert(b.getDate());
}
f1(a);
alert(a.getDate());
There are only function scopes in JS. Not block scopes!
You can see what is hoisting too.
var global_variable = "global_variable";
var hoisting_variable = "global_hoist";
// Global variables printed
console.log("global_scope: - global_variable: " + global_variable);
console.log("global_scope: - hoisting_variable: " + hoisting_variable);
if (true) {
// The variable block will be global, on true condition.
var block = "block";
}
console.log("global_scope: - block: " + block);
function local_function() {
var local_variable = "local_variable";
console.log("local_scope: - local_variable: " + local_variable);
console.log("local_scope: - global_variable: " + global_variable);
console.log("local_scope: - block: " + block);
// The hoisting_variable is undefined at the moment.
console.log("local_scope: - hoisting_variable: " + hoisting_variable);
var hoisting_variable = "local_hoist";
// The hoisting_variable is now set as a local one.
console.log("local_scope: - hoisting_variable: " + hoisting_variable);
}
local_function();
// No variable in a separate function is visible into the global scope.
console.log("global_scope: - local_variable: " + local_variable);
My understanding is that there are 3 scopes: global scope, available globally; local scope, available to an entire function regardless of blocks; and block scope, only available to the block, statement, or expression on which it was used. Global and local scope are indicated with the keyword 'var', either within a function or outside, and block scope is indicated with the keyword 'let'.
For those that believe there is only global and local scope, please explain why Mozilla would have an entire page describing the nuances of block scope in JS.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
In JavaScript there are two types of scope:
Local scope
Global scope
The Below function has a local scope variable carName. And this variable is not accessible from outside of the function.
function myFunction() {
var carName = "Volvo";
alert(carName);
// code here can use carName
}
The Below Class has a Global scope variable carName. And this variable is accessible from everywhere in the class.
class {
var carName = " Volvo";
// code here can use carName
function myFunction() {
alert(carName);
// code here can use carName
}
}
ES5 and earlier:
Variables in Javascript were initially (pre ES6) lexically function scoped. The term lexically scoped means that you can see the scope of the variables by 'looking' at the code.
Every variable declared with the var keyword is scoped to the function. However, if other function are declared within that function those functions will have access to the variables of the outer functions. This is called a scope chain. It works in the following manner:
When a function look to resolve a variable value it first looks at its own scope. This is the function body, i.e. everything between curly brackets {} (except for variables inside other functions which are in this scope).
If it cannot find the variable inside the function body it will climb up to the chain and look at the variable scope in the function in where the function was defined. This is what is meant with lexical scope, we can see in the code where this function was defined and thus can determine the scope chain by merely looking at the code.
Example:
// global scope
var foo = 'global';
var bar = 'global';
var foobar = 'global';
function outerFunc () {
// outerFunc scope
var foo = 'outerFunc';
var foobar = 'outerFunc';
innerFunc();
function innerFunc(){
// innerFunc scope
var foo = 'innerFunc';
console.log(foo);
console.log(bar);
console.log(foobar);
}
}
outerFunc();
What happens when we are trying to log the variables foo, bar, and foobar to the console is the following:
We try to log foo to the console, foo can be found inside the function innerFunc itself. Therefore, the value of foo is resolved to the string innerFunc.
We try to log bar to the console, bar cannot be found inside the function innerFunc itself. Therefore, we need to climb the scope chain. We first look in the outer function in which the function innerFunc was defined. This is the function outerFunc. In the scope of outerFunc we can find the variable bar, which holds the string 'outerFunc'.
foobar cannot be found in innerFunc. . Therefore, we need to climb the scope chain to the innerFunc scope. It also cannot be found here, we climb another level to the global scope (i.e. the outermost scope). We find the variable foobar here which holds the string 'global'. If it wouldnot have found the variable after climbing the scope chain the JS engine would throw a referenceError.
ES6 (ES 2015) and older:
The same concepts of lexically scope and scopechain still apply in ES6. However a new ways to declare variables were introduced. There are the following:
let: creates a block scoped variable
const: creates a block scoped variable which has to be initialized and cannot be reassigned
The biggest difference between var and let/const is that var is function scoped whereas let/const are block scoped. Here is an example to illustrate this:
let letVar = 'global';
var varVar = 'global';
function foo () {
if (true) {
// this variable declared with let is scoped to the if block, block scoped
let letVar = 5;
// this variable declared with let is scoped to the function block, function scoped
var varVar = 10;
}
console.log(letVar);
console.log(varVar);
}
foo();
In the above example letVar logs the value global because variables declared with let are block scoped. They cease to exist outside their respective block, so the variable can't be accessed outside the if block.
I really like the accepted answer but I want to add this:
Scope collects and maintains a look-up list of all the declared identifiers (variables), and enforces a strict set of rules as to how these are accessible to currently executing code.
Scope is a set of rules for looking up variables by their identifier name.
If a variable cannot be found in the immediate scope, Engine consults the next outer containing scope, continuing until is found or until the outermost (a.k.a., global) scope has been reached.
Is the set of rules that determines where and how a variable (identifier) can be looked up. This look-up may be for the purposes of assigning to the variable, which is an LHS (left-hand-side) reference, or it may be for the purposes of retrieving its value, which is an RHS (righthand-side) reference.
LHS references result from assignment operations. Scope-related assignments can occur either with the = operator or by passing arguments to (assign to) function parameters.
The JavaScript engine first compiles code before it executes, and in so doing, it splits up statements like var a = 2; into two separate steps: 1st. First, var a to declare it in that scope. This is performed at the beginning, before code execution. 2nd. Later, a = 2 to look up the variable (LHS reference) and assign to it if found.
Both LHS and RHS reference look-ups start at the currently executing scope, and if need be (that is, they don’t find what they’re looking for there), they work their way up the nested scope, one scope (floor) at a time, looking for the identifier, until they get to the global (top floor) and stop, and either find it, or don’t. Unfulfilled RHS references result in ReferenceError being thrown. Unfulfilled LHS references result in an automatic, implicitly created global of that name (if not in Strict Mode), or a ReferenceError (if in Strict Mode).
scope consists of a series of “bubbles” that each act as a container or bucket, in which identifiers (variables, functions) are declared. These bubbles nest neatly inside each other, and this nesting is defined at author time.
In EcmaScript5, there are mainly two scopes, local scope and global scope but in EcmaScript6 we have mainly three scopes, local scope, global scope and a new scope called block scope.
Example of block scope is :-
for ( let i = 0; i < 10; i++)
{
statement1...
statement2...// inside this scope we can access the value of i, if we want to access the value of i outside for loop it will give undefined.
}
ECMAScript 6 introduced the let and const keywords. These keywords can be used in place of the var keyword. Contrary to the var keyword, the let and const keywords support the declaration of local scope inside block statements.
var x = 10
let y = 10
const z = 10
{
x = 20
let y = 20
const z = 20
{
x = 30
// x is in the global scope because of the 'var' keyword
let y = 30
// y is in the local scope because of the 'let' keyword
const z = 30
// z is in the local scope because of the 'const' keyword
console.log(x) // 30
console.log(y) // 30
console.log(z) // 30
}
console.log(x) // 30
console.log(y) // 20
console.log(z) // 20
}
console.log(x) // 30
console.log(y) // 10
console.log(z) // 10
(function foo() { console.log(foo) })();
console.log(typeof foo); // undefined, because `foo` is scoped to its own expression
//but, like this
(function foo() {
console.log('1:', foo) // function foo
foo = 100
console.log('2:', foo) // function foo, is not 100, why?
})()
There are two types of scopes in JavaScript.
Global scope: variable which is announced in global scope can be used anywhere in the program very smoothly. For example:
var carName = " BMW";
// code here can use carName
function myFunction() {
// code here can use carName
}
Functional scope or Local scope: variable declared in this scope can be used in its own function only. For example:
// code here can not use carName
function myFunction() {
var carName = "BMW";
// code here can use carName
}

Pass by Reference in Haskell?

Coming from a C# background, I would say that the ref keyword is very useful in certain situations where changes to a method parameter are desired to directly influence the passed value for value types of for setting a parameter to null.
Also, the out keyword can come in handy when returning a multitude of various logically unconnected values.
My question is: is it possible to pass a parameter to a function by reference in Haskell? If not, what is the direct alternative (if any)?
There is no difference between "pass-by-value" and "pass-by-reference" in languages like Haskell and ML, because it's not possible to assign to a variable in these languages. It's not possible to have "changes to a method parameter" in the first place in influence any passed variable.
It depends on context. Without any context, no, you can't (at least not in the way you mean). With context, you may very well be able to do this if you want. In particular, if you're working in IO or ST, you can use IORef or STRef respectively, as well as mutable arrays, vectors, hash tables, weak hash tables (IO only, I believe), etc. A function can take one or more of these and produce an action that (when executed) will modify the contents of those references.
Another sort of context, StateT, gives the illusion of a mutable "state" value implemented purely. You can use a compound state and pass around lenses into it, simulating references for certain purposes.
My question is: is it possible to pass a parameter to a function by reference in Haskell? If not, what is the direct alternative (if any)?
No, values in Haskell are immutable (well, the do notation can create some illusion of mutability, but it all happens inside a function and is an entirely different topic). If you want to change the value, you will have to return the changed value and let the caller deal with it. For instance, see the random number generating function next that returns the value and the updated RNG.
Also, the out keyword can come in handy when returning a multitude of various logically unconnected values.
Consequently, you can't have out either. If you want to return several entirely disconnected values (at which point you should probably think why are disconnected values being returned from a single function), return a tuple.
No, it's not possible, because Haskell variables are immutable, therefore, the creators of Haskell must have reasoned there's no point of passing a reference that cannot be changed.
consider a Haskell variable:
let x = 37
In order to change this, we need to make a temporary variable, and then set the first variable to the temporary variable (with modifications).
let tripleX = x * 3
let x = tripleX
If Haskell had pass by reference, could we do this?
The answer is no.
Suppose we tried:
tripleVar :: Int -> IO()
tripleVar var = do
let times_3 = var * 3
let var = times_3
The problem with this code is the last line; Although we can imagine the variable being passed by reference, the new variable isn't.
In other words, we're introducing a new local variable with the same name;
Take a look again at the last line:
let var = times_3
Haskell doesn't know that we want to "change" a global variable; since we can't reassign it, we are creating a new variable with the same name on the local scope, thus not changing the reference. :-(
tripleVar :: Int -> IO()
tripleVar var = do
let tripleVar = var
let var = tripleVar * 3
return()
main = do
let x = 4
tripleVar x
print x -- 4 :(

Explanation of currying in simple terms [duplicate]

I've seen references to curried functions in several articles and blogs but I can't find a good explanation (or at least one that makes sense!)
Currying is when you break down a function that takes multiple arguments into a series of functions that each take only one argument. Here's an example in JavaScript:
function add (a, b) {
return a + b;
}
add(3, 4); // returns 7
This is a function that takes two arguments, a and b, and returns their sum. We will now curry this function:
function add (a) {
return function (b) {
return a + b;
}
}
This is a function that takes one argument, a, and returns a function that takes another argument, b, and that function returns their sum.
add(3)(4); // returns 7
var add3 = add(3); // returns a function
add3(4); // returns 7
The first statement returns 7, like the add(3, 4) statement.
The second statement defines a new function called add3 that will
add 3 to its argument. (This is what some may call a closure.)
The third statement uses the add3 operation to add 3 to 4, again
producing 7 as a result.
In an algebra of functions, dealing with functions that take multiple arguments (or equivalent one argument that's an N-tuple) is somewhat inelegant -- but, as Moses Schönfinkel (and, independently, Haskell Curry) proved, it's not needed: all you need are functions that take one argument.
So how do you deal with something you'd naturally express as, say, f(x,y)? Well, you take that as equivalent to f(x)(y) -- f(x), call it g, is a function, and you apply that function to y. In other words, you only have functions that take one argument -- but some of those functions return other functions (which ALSO take one argument;-).
As usual, wikipedia has a nice summary entry about this, with many useful pointers (probably including ones regarding your favorite languages;-) as well as slightly more rigorous mathematical treatment.
Here's a concrete example:
Suppose you have a function that calculates the gravitational force acting on an object. If you don't know the formula, you can find it here. This function takes in the three necessary parameters as arguments.
Now, being on the earth, you only want to calculate forces for objects on this planet. In a functional language, you could pass in the mass of the earth to the function and then partially evaluate it. What you'd get back is another function that takes only two arguments and calculates the gravitational force of objects on earth. This is called currying.
It can be a way to use functions to make other functions.
In javascript:
let add = function(x){
return function(y){
return x + y
};
};
Would allow us to call it like so:
let addTen = add(10);
When this runs the 10 is passed in as x;
let add = function(10){
return function(y){
return 10 + y
};
};
which means we are returned this function:
function(y) { return 10 + y };
So when you call
addTen();
you are really calling:
function(y) { return 10 + y };
So if you do this:
addTen(4)
it's the same as:
function(4) { return 10 + 4} // 14
So our addTen() always adds ten to whatever we pass in. We can make similar functions in the same way:
let addTwo = add(2) // addTwo(); will add two to whatever you pass in
let addSeventy = add(70) // ... and so on...
Now the obvious follow up question is why on earth would you ever want to do that? It turns what was an eager operation x + y into one that can be stepped through lazily, meaning we can do at least two things
1. cache expensive operations
2. achieve abstractions in the functional paradigm.
Imagine our curried function looked like this:
let doTheHardStuff = function(x) {
let z = doSomethingComputationallyExpensive(x)
return function (y){
z + y
}
}
We could call this function once, then pass around the result to be used in lots of places, meaning we only do the computationally expensive stuff once:
let finishTheJob = doTheHardStuff(10)
finishTheJob(20)
finishTheJob(30)
We can get abstractions in a similar way.
Currying is a transformation that can be applied to functions to allow them to take one less argument than previously.
For example, in F# you can define a function thus:-
let f x y z = x + y + z
Here function f takes parameters x, y and z and sums them together so:-
f 1 2 3
Returns 6.
From our definition we can can therefore define the curry function for f:-
let curry f = fun x -> f x
Where 'fun x -> f x' is a lambda function equivilent to x => f(x) in C#. This function inputs the function you wish to curry and returns a function which takes a single argument and returns the specified function with the first argument set to the input argument.
Using our previous example we can obtain a curry of f thus:-
let curryf = curry f
We can then do the following:-
let f1 = curryf 1
Which provides us with a function f1 which is equivilent to f1 y z = 1 + y + z. This means we can do the following:-
f1 2 3
Which returns 6.
This process is often confused with 'partial function application' which can be defined thus:-
let papply f x = f x
Though we can extend it to more than one parameter, i.e.:-
let papply2 f x y = f x y
let papply3 f x y z = f x y z
etc.
A partial application will take the function and parameter(s) and return a function that requires one or more less parameters, and as the previous two examples show is implemented directly in the standard F# function definition so we could achieve the previous result thus:-
let f1 = f 1
f1 2 3
Which will return a result of 6.
In conclusion:-
The difference between currying and partial function application is that:-
Currying takes a function and provides a new function accepting a single argument, and returning the specified function with its first argument set to that argument. This allows us to represent functions with multiple parameters as a series of single argument functions. Example:-
let f x y z = x + y + z
let curryf = curry f
let f1 = curryf 1
let f2 = curryf 2
f1 2 3
6
f2 1 3
6
Partial function application is more direct - it takes a function and one or more arguments and returns a function with the first n arguments set to the n arguments specified. Example:-
let f x y z = x + y + z
let f1 = f 1
let f2 = f 2
f1 2 3
6
f2 1 3
6
A curried function is a function of several arguments rewritten such that it accepts the first argument and returns a function that accepts the second argument and so on. This allows functions of several arguments to have some of their initial arguments partially applied.
Currying means to convert a function of N arity into N functions of arity 1. The arity of the function is the number of arguments it requires.
Here is the formal definition:
curry(f) :: (a,b,c) -> f(a) -> f(b)-> f(c)
Here is a real world example that makes sense:
You go to ATM to get some money. You swipe your card, enter pin number and make your selection and then press enter to submit the "amount" alongside the request.
here is the normal function for withdrawing money.
const withdraw=(cardInfo,pinNumber,request){
// process it
return request.amount
}
In this implementation function expects us entering all arguments at once. We were going to swipe the card, enter the pin and make the request, then function would run. If any of those steps had issue, you would find out after you enter all the arguments. With curried function, we would create higher arity, pure and simple functions. Pure functions will help us easily debug our code.
this is Atm with curried function:
const withdraw=(cardInfo)=>(pinNumber)=>(request)=>request.amount
ATM, takes the card as input and returns a function that expects pinNumber and this function returns a function that accepts the request object and after the successful process, you get the amount that you requested. Each step, if you had an error, you will easily predict what went wrong. Let's say you enter the card and got error, you know that it is either related to the card or machine but not the pin number. Or if you entered the pin and if it does not get accepted you know that you entered the pin number wrong. You will easily debug the error.
Also, each function here is reusable, so you can use the same functions in different parts of your project.
Currying is translating a function from callable as f(a, b, c) into callable as f(a)(b)(c).
Otherwise currying is when you break down a function that takes multiple arguments into a series of functions that take part of the arguments.
Literally, currying is a transformation of functions: from one way of calling into another. In JavaScript, we usually make a wrapper to keep the original function.
Currying doesn’t call a function. It just transforms it.
Let’s make curry function that performs currying for two-argument functions. In other words, curry(f) for two-argument f(a, b) translates it into f(a)(b)
function curry(f) { // curry(f) does the currying transform
return function(a) {
return function(b) {
return f(a, b);
};
};
}
// usage
function sum(a, b) {
return a + b;
}
let carriedSum = curry(sum);
alert( carriedSum(1)(2) ); // 3
As you can see, the implementation is a series of wrappers.
The result of curry(func) is a wrapper function(a).
When it is called like sum(1), the argument is saved in the Lexical Environment, and a new wrapper is returned function(b).
Then sum(1)(2) finally calls function(b) providing 2, and it passes the call to the original multi-argument sum.
Here's a toy example in Python:
>>> from functools import partial as curry
>>> # Original function taking three parameters:
>>> def display_quote(who, subject, quote):
print who, 'said regarding', subject + ':'
print '"' + quote + '"'
>>> display_quote("hoohoo", "functional languages",
"I like Erlang, not sure yet about Haskell.")
hoohoo said regarding functional languages:
"I like Erlang, not sure yet about Haskell."
>>> # Let's curry the function to get another that always quotes Alex...
>>> am_quote = curry(display_quote, "Alex Martelli")
>>> am_quote("currying", "As usual, wikipedia has a nice summary...")
Alex Martelli said regarding currying:
"As usual, wikipedia has a nice summary..."
(Just using concatenation via + to avoid distraction for non-Python programmers.)
Editing to add:
See http://docs.python.org/library/functools.html?highlight=partial#functools.partial,
which also shows the partial object vs. function distinction in the way Python implements this.
Here is the example of generic and the shortest version for function currying with n no. of params.
const add = a => b => b ? add(a + b) : a;
const add = a => b => b ? add(a + b) : a;
console.log(add(1)(2)(3)(4)());
Currying is one of the higher-order functions of Java Script.
Currying is a function of many arguments which is rewritten such that it takes the first argument and return a function which in turns uses the remaining arguments and returns the value.
Confused?
Let see an example,
function add(a,b)
{
return a+b;
}
add(5,6);
This is similar to the following currying function,
function add(a)
{
return function(b){
return a+b;
}
}
var curryAdd = add(5);
curryAdd(6);
So what does this code means?
Now read the definition again,
Currying is a function of many arguments which is rewritten such that it takes first argument and return a function which in turns uses the remaining arguments and returns the value.
Still, Confused?
Let me explain in deep!
When you call this function,
var curryAdd = add(5);
It will return you a function like this,
curryAdd=function(y){return 5+y;}
So, this is called higher-order functions. Meaning, Invoking one function in turns returns another function is an exact definition for higher-order function. This is the greatest advantage for the legend, Java Script.
So come back to the currying,
This line will pass the second argument to the curryAdd function.
curryAdd(6);
which in turns results,
curryAdd=function(6){return 5+6;}
// Which results in 11
Hope you understand the usage of currying here.
So, Coming to the advantages,
Why Currying?
It makes use of code reusability.
Less code, Less Error.
You may ask how it is less code?
I can prove it with ECMA script 6 new feature arrow functions.
Yes! ECMA 6, provide us with the wonderful feature called arrow functions,
function add(a)
{
return function(b){
return a+b;
}
}
With the help of the arrow function, we can write the above function as follows,
x=>y=>x+y
Cool right?
So, Less Code and Fewer bugs!!
With the help of these higher-order function one can easily develop a bug-free code.
I challenge you!
Hope, you understood what is currying. Please feel free to comment over here if you need any clarifications.
Thanks, Have a nice day!
If you understand partial you're halfway there. The idea of partial is to preapply arguments to a function and give back a new function that wants only the remaining arguments. When this new function is called it includes the preloaded arguments along with whatever arguments were supplied to it.
In Clojure + is a function but to make things starkly clear:
(defn add [a b] (+ a b))
You may be aware that the inc function simply adds 1 to whatever number it's passed.
(inc 7) # => 8
Let's build it ourselves using partial:
(def inc (partial add 1))
Here we return another function that has 1 loaded into the first argument of add. As add takes two arguments the new inc function wants only the b argument -- not 2 arguments as before since 1 has already been partially applied. Thus partial is a tool from which to create new functions with default values presupplied. That is why in a functional language functions often order arguments from general to specific. This makes it easier to reuse such functions from which to construct other functions.
Now imagine if the language were smart enough to understand introspectively that add wanted two arguments. When we passed it one argument, rather than balking, what if the function partially applied the argument we passed it on our behalf understanding that we probably meant to provide the other argument later? We could then define inc without explicitly using partial.
(def inc (add 1)) #partial is implied
This is the way some languages behave. It is exceptionally useful when one wishes to compose functions into larger transformations. This would lead one to transducers.
Curry can simplify your code. This is one of the main reasons to use this. Currying is a process of converting a function that accepts n arguments into n functions that accept only one argument.
The principle is to pass the arguments of the passed function, using the closure (closure) property, to store them in another function and treat it as a return value, and these functions form a chain, and the final arguments are passed in to complete the operation.
The benefit of this is that it can simplify the processing of parameters by dealing with one parameter at a time, which can also improve the flexibility and readability of the program. This also makes the program more manageable. Also dividing the code into smaller pieces would make it reuse-friendly.
For example:
function curryMinus(x)
{
return function(y)
{
return x - y;
}
}
var minus5 = curryMinus(1);
minus5(3);
minus5(5);
I can also do...
var minus7 = curryMinus(7);
minus7(3);
minus7(5);
This is very great for making complex code neat and handling of unsynchronized methods etc.
I found this article, and the article it references, useful, to better understand currying:
http://blogs.msdn.com/wesdyer/archive/2007/01/29/currying-and-partial-function-application.aspx
As the others mentioned, it is just a way to have a one parameter function.
This is useful in that you don't have to assume how many parameters will be passed in, so you don't need a 2 parameter, 3 parameter and 4 parameter functions.
As all other answers currying helps to create partially applied functions. Javascript does not provide native support for automatic currying. So the examples provided above may not help in practical coding. There is some excellent example in livescript (Which essentially compiles to js)
http://livescript.net/
times = (x, y) --> x * y
times 2, 3 #=> 6 (normal use works as expected)
double = times 2
double 5 #=> 10
In above example when you have given less no of arguments livescript generates new curried function for you (double)
A curried function is applied to multiple argument lists, instead of just
one.
Here is a regular, non-curried function, which adds two Int
parameters, x and y:
scala> def plainOldSum(x: Int, y: Int) = x + y
plainOldSum: (x: Int,y: Int)Int
scala> plainOldSum(1, 2)
res4: Int = 3
Here is similar function that’s curried. Instead
of one list of two Int parameters, you apply this function to two lists of one
Int parameter each:
scala> def curriedSum(x: Int)(y: Int) = x + y
curriedSum: (x: Int)(y: Int)Intscala> second(2)
res6: Int = 3
scala> curriedSum(1)(2)
res5: Int = 3
What’s happening here is that when you invoke curriedSum, you actually get two traditional function invocations back to back. The first function
invocation takes a single Int parameter named x , and returns a function
value for the second function. This second function takes the Int parameter
y.
Here’s a function named first that does in spirit what the first traditional
function invocation of curriedSum would do:
scala> def first(x: Int) = (y: Int) => x + y
first: (x: Int)(Int) => Int
Applying 1 to the first function—in other words, invoking the first function
and passing in 1 —yields the second function:
scala> val second = first(1)
second: (Int) => Int = <function1>
Applying 2 to the second function yields the result:
scala> second(2)
res6: Int = 3
An example of currying would be when having functions you only know one of the parameters at the moment:
For example:
func aFunction(str: String) {
let callback = callback(str) // signature now is `NSData -> ()`
performAsyncRequest(callback)
}
func callback(str: String, data: NSData) {
// Callback code
}
func performAsyncRequest(callback: NSData -> ()) {
// Async code that will call callback with NSData as parameter
}
Here, since you don't know the second parameter for callback when sending it to performAsyncRequest(_:) you would have to create another lambda / closure to send that one to the function.
Most of the examples in this thread are contrived (adding numbers). These are useful for illustrating the concept, but don't motivate when you might actually use currying in an app.
Here's a practical example from React, the JavaScript user interface library. Currying here illustrates the closure property.
As is typical in most user interface libraries, when the user clicks a button, a function is called to handle the event. The handler typically modifies the application's state and triggers the interface to re-render.
Lists of items are common user interface components. Each item might have an identifier associated with it (usually related to a database record). When the user clicks a button to, for example, "like" an item in the list, the handler needs to know which button was clicked.
Currying is one approach for achieving the binding between id and handler. In the code below, makeClickHandler is a function that accepts an id and returns a handler function that has the id in its scope.
The inner function's workings aren't important for this discussion. But if you're curious, it searches through the array of items to find an item by id and increments its "likes", triggering another render by setting the state. State is immutable in React so it takes a bit more work to modify the one value than you might expect.
You can think of invoking the curried function as "stripping" off the outer function to expose an inner function ready to be called. That new inner function is the actual handler passed to React's onClick. The outer function is a closure for the loop body to specify the id that will be in scope of a particular inner handler function.
const List = () => {
const [items, setItems] = React.useState([
{name: "foo", likes: 0},
{name: "bar", likes: 0},
{name: "baz", likes: 0},
].map(e => ({...e, id: crypto.randomUUID()})));
// .----------. outer func inner func
// | currying | | |
// `----------` V V
const makeClickHandler = (id) => (event) => {
setItems(prev => {
const i = prev.findIndex(e => e.id === id);
const cpy = {...prev[i]};
cpy.likes++;
return [
...prev.slice(0, i),
cpy,
...prev.slice(i + 1)
];
});
};
return (
<ul>
{items.map(({name, likes, id}) =>
<li key={id}>
<button
onClick={
/* strip off first function layer to get a click
handler bound to `id` and pass it to onClick */
makeClickHandler(id)
}
>
{name} ({likes} likes)
</button>
</li>
)}
</ul>
);
};
ReactDOM.createRoot(document.querySelector("#app"))
.render(<List />);
button {
font-family: monospace;
font-size: 2em;
}
<script crossorigin src="https://unpkg.com/react#18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-dom.development.js"></script>
<div id="app"></div>
Here you can find a simple explanation of currying implementation in C#. In the comments, I have tried to show how currying can be useful:
public static class FuncExtensions {
public static Func<T1, Func<T2, TResult>> Curry<T1, T2, TResult>(this Func<T1, T2, TResult> func)
{
return x1 => x2 => func(x1, x2);
}
}
//Usage
var add = new Func<int, int, int>((x, y) => x + y).Curry();
var func = add(1);
//Obtaining the next parameter here, calling later the func with next parameter.
//Or you can prepare some base calculations at the previous step and then
//use the result of those calculations when calling the func multiple times
//with different input parameters.
int result = func(1);
"Currying" is the process of taking the function of multiple arguments and converting it into a series of functions that each take a single argument and return a function of a single argument, or in the case of the final function, return the actual result.
The other answers have said what currying is: passing fewer arguments to a curried function than it expects is not an error, but instead returns a function that expects the rest of the arguments and returns the same result as if you had passed them all in at once.
I’ll try to motivate why it’s useful. It’s one of those tools that you never realized you needed until you do. Currying is above all a way to make your programs more expressive - you can combine operations together with less code.
For example, if you have a curried function add, you can write the equivalent of JS x => k + x (or Python lambda x: k + x or Ruby { |x| k + x } or Lisp (lambda (x) (+ k x)) or …) as just add(k). In Haskelll you can even use the operator: (k +) or (+ k) (The two forms let you curry either way for non-commutative operators: (/ 9) is a function that divides a number by 9, which is probably the more common use case, but you also have (9 /) for a function that divides 9 by its argument.) Besides being shorter, the curried version contains no made-up parameter name like the x found in all the other versions. It’s not needed. You’re defining a function that adds some constant k to a number, and you don’t need to give that number a name just to talk about the function. Or even to define it. This is an example of what’s called “point-free style”. You can combine operations together given nothing but the operations themselves. You don’t have to declare anonymous functions that do nothing but apply some operation to their argument, because *that’s what the operations already are.
This becomes very handy with higher-order functions when they’re defined in a currying-friendly way. For instance, a curried map(fn, list) let’s you define a mapper with just map(fn) that can be applied it to any list later. But currying a map defined instead as map(list, fn) just lets you define a function that will apply some other function to a constant list, which is probably less generally useful.
Currying reduces the need for things like pipes and threading. In Clojure, you might define a temperature conversion function using the threading macro ->: (defn f2c (deg) (-> deg (- 32) (* 5) (/ 9)). That’s cool, it reads nicely left to right (“subtract 32, multiply by 5 and divide by 9.”) and you only have to mention the parameter twice instead of once for every suboperation… but it only works because -> is a macro that transforms the whole form syntactically before anything is evaluated. It turns into a regular nested expression behind the scenes: (/ (* (- deg 32) 5) 9). If the math ops were curried, you wouldn’t need a macro to combine them so nicely, as in Haskell let f2c = (subtract 32) & (* 5) & (/ 9). (Although it would admittedly be more idiomatic to use function composition, which reads right to left: (/ 9) . (* 5) . (subtract 32).)
Again, it’s hard to find good demo examples; currying is most useful in complex cases where it really helps the readability of the solution, but those take so much explanation just to get you to understand the problem that the overall lesson about currying can get lost in the noise.
There is an example of "Currying in ReasonML".
let run = () => {
Js.log("Curryed function: ");
let sum = (x, y) => x + y;
Printf.printf("sum(2, 3) : %d\n", sum(2, 3));
let per2 = sum(2);
Printf.printf("per2(3) : %d\n", per2(3));
};
Below is one of currying example in JavaScript, here the multiply return the function which is used to multiply x by two.
const multiply = (presetConstant) => {
return (x) => {
return presetConstant * x;
};
};
const multiplyByTwo = multiply(2);
// now multiplyByTwo is like below function & due to closure property in JavaScript it will always be able to access 'presetConstant' value
// const multiplyByTwo = (x) => {
// return presetConstant * x;
// };
console.log(`multiplyByTwo(8) : ${multiplyByTwo(8)}`);
Output
multiplyByTwo(8) : 16

Groovy named and default arguments

Groovy supports both default, and named arguments. I just dont see them working together.
I need some classes to support construction using simple non named arguments, and using named arguments like below:
def a1 = new A(2)
def a2 = new A(a: 200, b: "non default")
class A extends SomeBase {
def props
A(a=1, b="str") {
_init(a, b)
}
A(args) {
// use the values in the args map:
_init(args.a, args.b)
props = args
}
private _init(a, b) {
}
}
Is it generally good practice to support both at the same time? Is the above code the only way to it?
The given code will cause some problems. In particular, it'll generate two constructors with a single Object parameter. The first constructor generates bytecode equivalent to:
A() // a,b both default
A(Object) // a set, b default
A(Object, Object) // pass in both
The second generates this:
A(Object) // accepts any object
You can get around this problem by adding some types. Even though groovy has dynamic typing, the type declarations in methods and constructors still matter. For example:
A(int a = 1, String b = "str") { ... }
A(Map args) { ... }
As for good practices, I'd simply use one of the groovy.transform.Canonical or groovy.transform.TupleConstructor annotations. They will provide correct property map and positional parameter constructors automatically. TupleConstructor provides the constructors only, Canonical applies some other best practices with regards to equals, hashCode, and toString.

Resources