Why does function composition compose from right to left in Javascript? - javascript

Function composition composes from right to left:
const comp = f => g => x => f(g(x));
const inc = x => x + 1;
const dec = x => x - 1;
const sqr = x => x * x;
let seq = comp(dec)(comp(sqr)(inc));
seq(2); // 8
seq(2) is transformed to dec(sqr(inc(2))) and the application order is inc(2)...sqr...dec. Thus the functions are invoked in the reverse order in which they are passed to comp. This isn't intuitive for Javascript programmers, since they're used to method chaining, which goes from left to right:
o = {
x: 2,
inc() { return this.x + 1, this },
dec() { return this.x - 1, this },
sqr() { return this.x * this.x, this }
}
o.dec().sqr().inc(); // 2
I consider that confusing. Here's a reversed composition:
const flipped = f => g => x => g(f(x));
let seql = flipped(dec)(flipped(sqr)(inc));
seql(2); // 2
Are there any reasons why function composition goes from right to left?

To answer the original question: Why does function composition compose from right to left?
So it is traditionally made in mathematics
comp(f)(g)(x) has the same order as f(g(x))
It is trivial to create a reversed or forward composition (see example)
Forward function composition:
const comp = f => g => x => f(g(x));
const flip = f => x => y => f(y)(x);
const flipped = flip(comp);
const inc = a => a + 1;
const sqr = b => b * b;
comp(sqr)(inc)(2); // 9, since 2 is first put into inc then sqr
flipped(sqr)(inc)(2); // 5, since 2 is first put into sqr then inc
This way of calling functions is called currying, and works like this:
// the original:
comp(sqr)(inc)(2); // 9
// is interpreted by JS as:
( ( ( comp(sqr) ) (inc) ) (2) ); // 9 still (yes, this actually executes!)
// it is even clearer when we separate it into discrete steps:
const compSqr = comp(sqr); // g => x => sqr(g(x))
compSqr(inc)(2); // 9 still
const compSqrInc = compSqr(inc); // x => sqr(x + 1)
compSqrInc(2); // 9 still
const compSqrInc2 = compSqrInc(2); // sqr(3)
compSqrInc2; // 9 still
So functions are composed and interpreted (by the JS interpreter) left to right, while on execution, their values flow through each function from right to left. In short: first outside-in, then inside-out.
But flip has the restriction that a flipped composition can't be combined with itself to form a "higher order composition":
const comp2 = comp(comp)(comp);
const flipped2 = flipped(flipped)(flipped);
const add = x => y => x + y;
comp2(sqr)(add)(2)(3); // 25
flipped2(sqr)(add)(2)(3); // "x => f(g(x))3" which is nonsense
Conclusion: The right-to-left order is traditional/conventional but not intuitive.

Your question is actually about the order of arguments in a definition of the function composition operator rather than right- or left-associativity. In mathematics, we usually write "f o g" (equivalent to comp(f)(g) in your definition) to mean the function that takes x and returns f(g(x)). Thus "f o (g o h)" and "(f o g) o h" are equivalent and both mean the function that maps each argument x to f(g(h(x))).
That said, we sometimes write f;g (equivalent to compl(f)(g) in your code) to mean the function which maps x to g(f(x)). Thus, both (f;g);h and f;(g;h) mean the function mapping x to h(g(f(x))).
A reference: https://en.wikipedia.org/wiki/Function_composition#Alternative_notations

Related

Printing curried function doesn't show the captured parameter

If I define a curried function like this:
const gt = x => y => y > x
I would expect gt(5) returns y => y > 5
but gt(5) (or gt(5).toString()) returns y => y > x
How do I get the captured parameter?
I would expect gt(5) returns y => y > 5
That isn't how JavaScript works. The code of the function returned by gt(5) is y => y > x, it's just that that code executes in an environment where the identifer x resolves to a binding that has the value 5 because it's a closure over that environment. toString on functions returns a string version of the source code of the function (or a function declaration around the [ native code ]) (spec), so you still see y => y > x. The string returned by toString doesn't include the environment in which that code runs.
See also:
How do JavaScript's closures work? - here on SO
Closures are not complicated - on my old anemic blog (uses some outdated terminology, I should probably fix that)
As #VLAZ points out in a comment, you can override the default toString on a function to give it the behavior you want. If you don't mind duplication (which almost inevitably leads to maintenance issues):
const gt = x => {
const fn = y => y > x;
fn.toString = () => `y => y > ${x}`;
return fn;
};
console.log(String(gt(5)));
...or if you want to define toString with the same enumerability, etc., as the version on the prototype:
Object.defineProperty(fn, "toString", {
value: () => `y => y > ${x}`,
writable: true,
configurable: true,
});
Doing that in the general case requires a proper JavaScript parser to do the substitution.
It's not possible to just print a variable captured in a closure, however there is a workaround for curry. I will be referring to Brian Lonsdorf's article on Medium Debugging Functional which goes into more details about curry and compose. I heartily recommend reading the article itself, as I will only use the essentials.
Brian Lonsdorf proposes a custom implementation of a general curry function. The original version is taken from an article by Erin Swenson-Healy.
Here is the modified version:
function fToString(f) {
return f.name ? f.name : `(${f.toString()})`;
}
function curry(fx) {
var arity = fx.length;
function f1() {
var args = Array.prototype.slice.call(arguments, 0);
if (args.length >= arity) return fx.apply(null, args);
function f2() {
return f1.apply(null, args.concat(Array.prototype.slice.call(arguments, 0)));
}
f2.toString = function() {
return fToString(fx)+'('+args.join(', ')+')';
}
return f2;
};
f1.toString = function() { return fToString(fx); }
return f1;
}
const gt = curry((x, y) => y > x);
const sum3 = curry((x, y, z) => x + y + z);
const ltUncurried = (x, y) => y < x;
const lt = curry(ltUncurried);
console.log(gt(1)); // ((x, y) => y > x)(1)
console.log(sum3(1)); // ((x, y, z) => x + y + z)(1)
console.log(sum3(1, 2)); // ((x, y, z) => x + y + z)(1, 2)
console.log(sum3(1)(2)); // ((x, y, z) => x + y + z)(1, 2)
console.log(lt(1)); // ltUncurried(1)
(I have modified fToString() to include brackets around f.toString() for better readability)
This is quite flexible as it allows currying any function but also provides better logging of said function. The toString implementation can be modified if required for whatever you deem are the most important details.
const gt = x => y => y > x
gt(1);
If you had pass only 1 argument like gt(1) and if you Check in console, x = 1, y is not available at this time. So the execution context (call stack) will show only the x argument and for the gt() method it will only show the code (y > x).
And here below gives us a hint that gt(1) will first bind x to 1, and return a new function f(y) = y > x = y > 1
You didn't second pass second argument, It means now the function f(y) = 1 + y is executed, and this time, it will check for the y where y is not available at that time. And the argument x’s value 1 is still preserved in the context via Closure.
It's look like same as below closure function :-
function add(x) {
return function (y) {
return y > x
}
}
var d = add(1)(2); ===>>>> true

How to reconcile Javascript with currying and function composition

I love currying but there are a couple of reasons why a lof of Javascript devs reject this technique:
aesthetic concerns about the typical curry pattern: f(x) (y) (z)
concerns about performance penalties due to the increased number of function calls
concerns about debugging issues because of the many nested anonymous functions
concerns about readability of point-free style (currying in connection with composition)
Is there an approach that can mitigate these concerns so that my coworkers don't hate me?
Note: #ftor answered his/her own question. This is a direct companion to that answer.
You're already a genius
I think you might've re-imagined the partial function – at least, in part!
const partial = (f, ...xs) => (...ys) => f(...xs, ...ys);
and it's counter-part, partialRight
const partialRight = (f, ...xs) => (...ys) => f(...ys, ...xs);
partial takes a function, some args (xs), and always returns a function that takes some more args (ys), then applies f to (...xs, ...ys)
Initial remarks
The context of this question is set in how currying and composition can play nice with a large user base of coders. My remarks will be in the same context
just because a function may return a function does not mean that it is curried – tacking on a _ to signify that a function is waiting for more args is confusing. Recall that currying (or partial function application) abstracts arity, so we never know when a function call will result in the value of a computation or another function waiting to be called.
curry should not flip arguments; that is going to cause some serious wtf moments for your fellow coder
if we're going to create a wrapper for reduce, the reduceRight wrapper should be consistent – eg, your foldl uses f(acc, x, i) but your foldr uses f(x, acc, i) – this will cause a lot of pain amongst coworkers that aren't familiar with these choices
For the next section, I'm going to replace your composable with partial, remove _-suffixes, and fix the foldr wrapper
Composable functions
const partial = (f, ...xs) => (...ys) => f(...xs, ...ys);
const partialRight = (f, ...xs) => (...ys) => f(...ys, ...xs);
const comp = (f, g) => x => f(g(x));
const foldl = (f, acc, xs) => xs.reduce(f, acc);
const drop = (xs, n) => xs.slice(n);
const add = (x, y) => x + y;
const sum = partial(foldl, add, 0);
const dropAndSum = comp(sum, partialRight(drop, 1));
console.log(
dropAndSum([1,2,3,4]) // 9
);
Programmatic solution
const partial = (f, ...xs) => (...ys) => f(...xs, ...ys);
// restore consistent interface
const foldr = (f, acc, xs) => xs.reduceRight(f, acc);
const comp = (f,g) => x => f(g(x));
// added this for later
const flip = f => (x,y) => f(y,x);
const I = x => x;
const inc = x => x + 1;
const compn = partial(foldr, flip(comp), I);
const inc3 = compn([inc, inc, inc]);
console.log(
inc3(0) // 3
);
A more serious task
const partial = (f, ...xs) => (...ys) => f(...xs, ...ys);
const filter = (f, xs) => xs.filter(f);
const comp2 = (f, g, x, y) => f(g(x, y));
const len = xs => xs.length;
const odd = x => x % 2 === 1;
const countWhere = f => partial(comp2, len, filter, f);
const countWhereOdd = countWhere(odd);
console.log(
countWhereOdd([1,2,3,4,5]) // 3
);
Partial power !
partial can actually be applied as many times as needed
const partial = (f, ...xs) => (...ys) => f(...xs, ...ys)
const p = (a,b,c,d,e,f) => a + b + c + d + e + f
let f = partial(p,1,2)
let g = partial(f,3,4)
let h = partial(g,5,6)
console.log(p(1,2,3,4,5,6)) // 21
console.log(f(3,4,5,6)) // 21
console.log(g(5,6)) // 21
console.log(h()) // 21
This makes it an indispensable tool for working with variadic functions, too
const partial = (f, ...xs) => (...ys) => f(...xs, ...ys)
const add = (x,y) => x + y
const p = (...xs) => xs.reduce(add, 0)
let f = partial(p,1,1,1,1)
let g = partial(f,2,2,2,2)
let h = partial(g,3,3,3,3)
console.log(h(4,4,4,4))
// 1 + 1 + 1 + 1 +
// 2 + 2 + 2 + 2 +
// 3 + 3 + 3 + 3 +
// 4 + 4 + 4 + 4 => 40
Lastly, a demonstration of partialRight
const partial = (f, ...xs) => (...ys) => f(...xs, ...ys);
const partialRight = (f, ...xs) => (...ys) => f(...ys, ...xs);
const p = (...xs) => console.log(...xs)
const f = partialRight(p, 7, 8, 9);
const g = partial(f, 1, 2, 3);
const h = partial(g, 4, 5, 6);
p(1, 2, 3, 4, 5, 6, 7, 8, 9) // 1 2 3 4 5 6 7 8 9
f(1, 2, 3, 4, 5, 6) // 1 2 3 4 5 6 7 8 9
g(4, 5, 6) // 1 2 3 4 5 6 7 8 9
h() // 1 2 3 4 5 6 7 8 9
Summary
OK, so partial is pretty much a drop in replacement for composable but also tackles some additional corner cases. Let's see how this bangs up against your initial list
aesthetic concerns: avoids f (x) (y) (z)
performance: unsure, but i suspect performance is about the same
debugging: still an issue because partial creates new functions
readability: i think readability here is pretty good, actually. partial is flexible enough to remove points in many cases
I agree with you that there's no replacement for fully curried functions. I personally found it easy to adopt the new style once I stopped being judgmental about the "ugliness" of the syntax – it's just different and people don't like different.
The current prevailing approach provides that each multi argument function is wrapped in a dynamic curry function. While this helps with concern #1, it leaves the remaining ones untouched. Here is an alternative approach.
Composable functions
A composable function is curried only in its last argument. To distinguish them from normal multi argument functions, I name them with a trailing underscore (naming is hard).
const comp_ = (f, g) => x => f(g(x)); // composable function
const foldl_ = (f, acc) => xs => xs.reduce((acc, x, i) => f(acc, x, i), acc);
const curry = f => y => x => f(x, y); // fully curried function
const drop = (xs, n) => xs.slice(n); // normal, multi argument function
const add = (x, y) => x + y;
const sum = foldl_(add, 0);
const dropAndSum = comp_(sum, curry(drop) (1));
console.log(
dropAndSum([1,2,3,4]) // 9
);
With the exception of drop, dropAndSum consists exclusively of multi argument or composable functions and yet we've achieved the same expressiveness as with fully curried functions - at least with this example.
You can see that each composable function expects either uncurried or other composable functions as arguments. This will increase speed especially for iterative function applications. However, this is also restrictive as soon as the result of a composable function is a function again. Look into the countWhere example below for more information.
Programmatic solution
Instead of defining composable functions manually we can easily implement a programmatic solution:
// generic functions
const composable = f => (...args) => x => f(...args, x);
const foldr = (f, acc, xs) =>
xs.reduceRight((acc, x, i) => f(x, acc, i), acc);
const comp_ = (f, g) => x => f(g(x));
const I = x => x;
const inc = x => x + 1;
// derived functions
const foldr_ = composable(foldr);
const compn_ = foldr_(comp_, I);
const inc3 = compn_([inc, inc, inc]);
// and run...
console.log(
inc3(0) // 3
);
Operator functions vs. higher order functions
Maybe you noticed that curry (form the first example) swaps arguments, while composable does not. curry is meant to be applied to operator functions like drop or sub only, which have a different argument order in curried and uncurried form respectively. An operator function is any function that expects only non-functional arguments. In this sence...
const I = x => x;
const eq = (x, y) => x === y; // are operator functions
// whereas
const A = (f, x) => f(x);
const U = f => f(f); // are not operator but a higher order functions
Higher order functions (HOFs) don't need swapped arguments but you will regularly encounter them with arities higher than two, hence the composbale function is useful.
HOFs are one of the most awesome tools in functional programming. They abstract from function application. This is the reason why we use them all the time.
A more serious task
We can solve more complex tasks as well:
// generic functions
const composable = f => (...args) => x => f(...args, x);
const filter = (f, xs) => xs.filter(f);
const comp2 = (f, g, x, y) => f(g(x, y));
const len = xs => xs.length;
const odd = x => x % 2 === 1;
// compositions
const countWhere_ = f => composable(comp2) (len, filter, f); // (A)
const countWhereOdd = countWhere_(odd);
// and run...
console.log(
countWhereOdd([1,2,3,4,5]) // 3
);
Please note that in line A we were forced to pass f explicitly. This is one of the drawbacks of composable against curried functions: Sometimes we need to pass the data explicitly. However, if you dislike point-free style, this is actually an advantage.
Conclusion
Making functions composable mitigates the following concerns:
aesthetic concerns (less frequent use of the curry pattern f(x) (y) (z)
performance penalties (far fewer function calls)
However, point #4 (readability) is only slightly improved (less point-free style) and point #3 (debugging) not at all.
While I am convinced that a fully curried approach is superior to the one presented here, I think composable higher order functions are worth thinking about. Just use them as long as you or your coworkers don't feel comfortable with proper currying.

lodash curry does not work on function returned by flow; lodash FP enough for FP?

Is the lodash flow function a real compose function, or is it something that looks like one, but is optimized to run fast and sacrifices the flexibility I'd expect? I expected flow to return a function I could curry, but instead it gave back a function that uses Javascript's arguments keyword. So curry can't tell that there are pending arguments, and it just gets invoked immediately.
Working intuitively enough:
var add = function(x, y) {
return x + y
};
var exclam = function(x) {
return x.toString() + "!";
}
exclam(1) // "1!"
add(1,2) // 3
var add1 = FP.curry(add)(1);
add1(4) // 5
var add1AndExclam = FP.flow([add1, exclam])
add1AndExclam(2) // "3!"
Non-intuitive result:
addAndExclam = FP.flow([add, exclam])
/*
function(){
var t=arguments,e=t[0];
if(i&&1==t.length&&yi(e)&&e.length>=200)return i.plant(e).value();
for(var u=0,t=r?n[u].apply(this,t):e;++u<r;)t=n[u].call(this,t);
return t
}
*/
addAndExclam(1,2) // "3!"
add1AndExclamV2 = FP.curry(addAndExclam)(1) // "NaN!"`
Is it overkill to look for another library to help with functional programming paradigms? Should I just whip up my own compose? I used lodash because it was already in my project. The documentation makes it look like flow should be lodash's compose.
I've also found it really difficult to curry the data argument in lodash's each (I wanted something like an eachMyArrayName shortcut). Whether I use curryRight or the lodash object placeholder convention.
Is lodash FP just for making lodash functions auto curriable? Or am I doing something wrong, and it is usable as the main functional programming helper?
Edit:
If I want to I can wrap the function like this, but it seems to defeat the purpose of meta programming to have boilerplate looking code.
add1AndExclamV2 = FP.curry(function(x, y) {
return addAndExclam(x, y)
})(1)
add1AndExclamV2(2)
"3!"`
This is just basic function composition. Lodash "flow" and Rambda "pipe" probably found it difficult to name these functions because they're not suitably generic. They're not "real" the same way you use the word real in the phrase "real compose function".
You can compose a binary function with a unary function using comp2 – the catch is, the "binary" function must be in curried form instead of taking a tuple
let f = x => y => ...
instead of
let f = (x,y) => ...
Recall that functional programming has its roots in the lambda calculus where there is no such thing as a function that takes anything other than 1 argument.
const curry = f => x => y => f (x,y)
const comp = f => g => x => f (g (x))
const comp2 = comp (comp) (comp)
var add = function(x, y) { return x + y };
var exclam = function(x) { return x.toString() + "!"; }
console.log(exclam (1)) // "1!"
console.log(add (1,2)) // 3
var add1 = curry (add) (1)
console.log(add1 (4)) // 5
var addAndExclam = comp2 (exclam) (curry (add))
console.log(addAndExclam (1) (2)) // "3!"
I encourage you to use the substitution model to see how the expression evaluates
Putting types on everything helps you reason about the program more effecitvely
// curry :: ((a,b) -> c) -> a -> b -> c
const curry = f => x => y => f (x,y)
// comp :: (b -> c) -> (a -> b) -> (a -> c)
const comp = f => g => x => f (g (x))
// comp2 :: (c -> d) -> (a -> b -> c) -> (a -> b -> d)
const comp2 = comp (comp) (comp)
// add :: (Number,Number) -> Number
var add = function(x, y) { return x + y };
// exclam :: Number -> String
var exclam = function(x) { return x.toString() + "!"; }
console.log(exclam (1)) // "1!"
console.log(add (1,2)) // 3
// add1 :: Number -> Number
var add1 = curry (add) (1)
console.log(add1 (4)) // 5
// addAndExlam :: Number -> Number -> String
var addAndExclam = comp2 (exclam) (curry (add))
console.log(addAndExclam (1) (2)) // "3!"
Regarding your comment:
I think if I wanted to compose a special function where one of the nested functions took two args, I would write it out
Good idea. If you find yourself looking around for a built-in procedure (provided by your language or some library), that should already be an indicator to you that you should try to write it out first. At least confirm with yourself that you're understanding your needs correctly.
This is perfectly acceptable
const addAndExclam = (x,y) => exclam (add (x,y))
And so is this
const addAndExclam = x => y => exclam (add (x,y))
If you later learn about comp2 and see that it could describe the code a little better, then you can implement it at that time
const addAndExclam = comp2 (exclam) (curry (add))
var myAdd = function(x, y) { return x + y; };
var exclam = function(x) { return x.toString() + '!'; };
var addSclam = pipe(myAdd, exclam);
addSclam(1,2); // "3!"
var add1Sclam = curry( addSclam )(1);
add1Sclam(500); // "501!"
It looks like ramda does what would have been intuitive to me. It adds another 1.2mb to my project, but I guess it could be used to more or less replace lodash.

Which parameter order with operators as pre-curried functions and composition in Javascript?

Given is a simple, mathematically curried function to subtract numbers:
function sub(x) {
return function (y) {
return x - y;
};
};
sub(3)(2); // 1
The function signature reads exactly as the obtained result. The situation changes as soon as function composition is involved:
function comp(f) {
return function (g) {
return function (x) {
return f(g(x));
};
};
};
function gte(x) {
return function (y) {
return x >= y;
};
};
comp(gte(2))(sub(3)) (4); // true
With function composition, the last parameter of each function involved is crucial, as it is fed respectively with the value returned by the previously applied function. The composition in the above example reads therefore as: 4 - 3 >= 2 which would yield false. In fact, the computation behind the composition is: 2 >= 3 - 4, which yields true.
I can rewrite sub and gte easily to get the desired result:
function sub(y) {
return function (x) {
return x - y;
};
};
function gte(y) {
return function (x) {
return x >= y;
};
};
comp(gte(2))(sub(3)) (4); // false
But now the return values of directly called functions are different than expected:
sub(3)(2); // -1 (but reads like 1)
gte(2)(3); // true (but reads like false)
I could switch the arguments for each call or define a partial applied function for each case:
function flip(f) {
return function (x) {
return function (y) {
return f(y)(x);
};
};
}
flip(gte)(2)(3); // false
var gteFlipped = flip(gte);
gteFlipped(2)(3); // false
Both variants are obviously cumbersome and neither more readable.
Which parameter order is preferable? Or is there a mechanism to use both, depending on the respective requirements (like Haskell's left/right sections for partially applied operators)?
A possible solution must take into account, that I use unary functions only!
So you want to partially apply operators without having to write code like:
var gte2 = function (x) { return x >= 2; };
That's a reasonable use case, “to partially apply operators”.
The answer is simple. Just write a curried function. For example:
// var gte = y => x => x >= y; // ES6 syntax
var gte = function (y) {
return function (x) {
return x >= y;
};
};
var gte2 = gte(2);
Unfortunately, there are two ways we can partially apply binary operators:
Partially apply the operator to the left argument.
Partially apply the operator to the right argument.
This raises two important questions:
Which argument should the operator be partially applied to by default?
How do we partially apply the operator to the other argument?
Fortunately, we can agree on one thing: it makes no sense to provide both arguments to the operator.
// Why write the following:
add(2)(3)
// When you can write the following:
2 + 3
The reason we are creating curried operator functions in the first place is for partial application.
Hence, it makes no sense to provide both arguments to the function “at once”.
What are the ramifications of this restriction? It means that:
We can choose any argument order we want.
// This is correct:
var sub = x => y => x - y;
// So is this:
var sub = y => x => x - y;
It only needs to make sense given one argument.
// Consider this operator function:
var sub = y => x => x - y;
// This makes sense:
sub(1) // means (x => x - 1)
// However, this doesn't make sense:
sub(2)(3) // expected (2 - 3) but actually (3 - 2)
// But that's OK because it only needs to make sense given one argument.
Now, keeping this in mind which is the best argument order? Well, it depends.
For commutative operations the argument order doesn't matter.
For example, both addition and multiplication are commutative. Hence, a + b = b + a for addition and a * b = b * a for multiplication.
For non-commutative operations the right-to-left argument order is generally better because it allows the partial application to be read out loud.
For example, the expression lt(2) generally means x => x < 2 and not x => 2 < x.
Why is this the general case? Well, in JavaScript function names come before the argument. Hence, name(arg) naturally reads as x => x name arg instead of x => arg name x.
However, there are some exceptions to the second rule. Most prominently, division:
div(10) // is read out loud as divide 10 by x
// it is not read out loud as divide x by 10
Of course, the correct argument order for such edge cases is a matter of debate but in my humble opinion the left-to-right argument order seems more natural.
So, here are a bunch of curried operator functions:
// Commutative operators:
var add = x => y => x + y;
var mul = x => y => x * y;
// Right-to-left operators:
var lt = y => x => x < y;
var gt = y => x => x > y;
var lte = y => x => x <= y;
var gte = y => x => x >= y;
var sub = y => x => x - y;
// Left-to-right operators:
var div = x => y => x / y;
Now, the second question is how do we partially apply the operators to “other” argument?
The only way to do so it to create a new function with the flipped argument order.
Fortunately, we don't need to create a new function for every operator:
For commutative operators the argument order doesn't matter. Hence:
flip(add) = add
flip(mul) = mul
For relational operators we don't need to create extra functions:
flip(lt) = gt
flip(gt) = lt
flip(lte) = gte
flip(gte) = lte
We only need to create flipped operator functions for sub and div:
var subFrom = x => y => x - y; // subFrom(5) means (y => 5 - y)
var divBy = y => x => x / y; // divBy(10) means (x => x / 10)
All things considered, I would say that you should use your common sense.
Here's how I read your composition:
comp(gte(2))(sub(3)) (4);
gte(2) = function(y) { return 2 >= y; } // (x = 2)
sub(3) = function(y) { return 3 - y; } // (x = 3)
// Therefore:
comp(gte(2))(sub(3)) = function(x) {
var f = function(y) { return 2 >= y; };
var g = function(y) { return 3 - y; };
return f(g(x));
};
// Now call with (x = 4):
x = 4
g(4) = 3 - 4 = -1
f(-1) = (2 >= -1) = true
So in short, it seems that your expectations are wrong. Maybe you do indeed have something backwards, but I honestly can't tell what. I do, however, think that this is not a good way to work in JavaScript and you're overcomplicating things, but that's just my opinion.
This response is based on the reply from Aadit.
There is actually a need for fully applied curried operator functions in Javascript - when used as First Class Citizens:
function between(ops) {
return function (left) {
return function (right) {
return function (n) {
// At this point one should use the native Javascript operators
// but they can't be passed to the function, since operators are not First Class.
return ops[0](left)(n) && ops[1](right)(n);
};
};
};
}
function lte(y) { return function (x) { return x <= y; }; }
function gt(y) { return function (x) { return x > y; }; }
between([gt, lte])(2)(4)(4); // true
// is evaluated as: gt(2)(4) && lte(4)(4) === true; (confusing)
between may be nonsense, but it serves as proof that fully applied curried operator functions make sense in Javascript. There are likely even other use cases.
Nevertheless Aadit is right that something like sub(2)(3) contradicts the very purpose of currying!
So how could a solution look like?
all curried operator functions must have a right-to-left argument order
a function is introduced, which explicitly indicates the unusual usage when passing all arguments to a curried function at once
Here is uncurryOp:
// intended for all operator functions
function uncurryOp(f) {
return function (x, y) {
return f(y)(x);
};
}
uncurryOp(gt)(2, 4); // false (intuitive)
This is not really an adequate solution. I think there is no, due to lack of First Class and partially applicable operators in Javascript.

javascript: recursive anonymous function?

Let's say I have a basic recursive function:
function recur(data) {
data = data+1;
var nothing = function() {
recur(data);
}
nothing();
}
How could I do this if I have an anonymous function such as...
(function(data){
data = data+1;
var nothing = function() {
//Something here that calls the function?
}
nothing();
})();
I'd like a way to call the function that called this function... I've seen scripts somewhere (I can't remember where) that can tell you the name of a function called, but I can't recall any of that information right now.
You can give the function a name, even when you're creating the function as a value and not a "function declaration" statement. In other words:
(function foo() { foo(); })();
is a stack-blowing recursive function. Now, that said, you probably don't may not want to do this in general because there are some weird problems with various implementations of Javascript. (note — that's a fairly old comment; some/many/all of the problems described in Kangax's blog post may be fixed in more modern browsers.)
When you give a name like that, the name is not visible outside the function (well, it's not supposed to be; that's one of the weirdnesses). It's like "letrec" in Lisp.
As for arguments.callee, that's disallowed in "strict" mode and generally is considered a bad thing, because it makes some optimizations hard. It's also much slower than one might expect.
edit — If you want to have the effect of an "anonymous" function that can call itself, you can do something like this (assuming you're passing the function as a callback or something like that):
asyncThingWithCallback(params, (function() {
function recursive() {
if (timeToStop())
return whatever();
recursive(moreWork);
}
return recursive;
})());
What that does is define a function with a nice, safe, not-broken-in-IE function declaration statement, creating a local function whose name will not pollute the global namespace. The wrapper (truly anonymous) function just returns that local function.
People talked about the Y combinator in comments, but no one wrote it as an answer.
The Y combinator can be defined in javascript as follows: (thanks to steamer25 for the link)
var Y = function (gen) {
return (function(f) {
return f(f);
}(function(f) {
return gen(function() {
return f(f).apply(null, arguments);
});
}));
}
And when you want to pass your anonymous function:
(Y(function(recur) {
return function(data) {
data = data+1;
var nothing = function() {
recur(data);
}
nothing();
}
})());
The most important thing to note about this solution is that you shouldn't use it.
U combinator
By passing a function to itself as an argument, a function can recur using its parameter instead of its name! So the function given to U should have at least one parameter that will bind to the function (itself).
In the example below, we have no exit condition, so we will just loop indefinitely until a stack overflow happens
const U = f => f (f) // call function f with itself as an argument
U (f => (console.log ('stack overflow imminent!'), U (f)))
We can stop the infinite recursion using a variety of techniques. Here, I'll write our anonymous function to return another anonymous function that's waiting for an input; in this case, some number. When a number is supplied, if it is greater than 0, we will continue recurring, otherwise return 0.
const log = x => (console.log (x), x)
const U = f => f (f)
// when our function is applied to itself, we get the inner function back
U (f => x => x > 0 ? U (f) (log (x - 1)) : 0)
// returns: (x => x > 0 ? U (f) (log (x - 1)) : 0)
// where f is a reference to our outer function
// watch when we apply an argument to this function, eg 5
U (f => x => x > 0 ? U (f) (log (x - 1)) : 0) (5)
// 4 3 2 1 0
What's not immediately apparent here is that our function, when first applied to itself using the U combinator, it returns a function waiting for the first input. If we gave a name to this, can effectively construct recursive functions using lambdas (anonymous functions)
const log = x => (console.log (x), x)
const U = f => f (f)
const countDown = U (f => x => x > 0 ? U (f) (log (x - 1)) : 0)
countDown (5)
// 4 3 2 1 0
countDown (3)
// 2 1 0
Only this isn't direct recursion – a function that calls itself using its own name. Our definition of countDown does not reference itself inside of its body and still recursion is possible
// direct recursion references itself by name
const loop = (params) => {
if (condition)
return someValue
else
// loop references itself to recur...
return loop (adjustedParams)
}
// U combinator does not need a named reference
// no reference to `countDown` inside countDown's definition
const countDown = U (f => x => x > 0 ? U (f) (log (x - 1)) : 0)
How to remove self-reference from an existing function using U combinator
Here I'll show you how to take a recursive function that uses a reference to itself and change it to a function that employs the U combinator to in place of the self reference
const factorial = x =>
x === 0 ? 1 : x * factorial (x - 1)
console.log (factorial (5)) // 120
Now using the U combinator to replace the inner reference to factorial
const U = f => f (f)
const factorial = U (f => x =>
x === 0 ? 1 : x * U (f) (x - 1))
console.log (factorial (5)) // 120
The basic replacement pattern is this. Make a mental note, we will be using a similar strategy in the next section
// self reference recursion
const foo = x => ... foo (nextX) ...
// remove self reference with U combinator
const foo = U (f => x => ... U (f) (nextX) ...)
Y combinator
related: the U and Y combinators explained using a mirror analogy
In the previous section we saw how to transform self-reference recursion into a recursive function that does not rely upon a named function using the U combinator. There's a bit of an annoyance tho with having to remember to always pass the function to itself as the first argument. Well, the Y-combinator builds upon the U-combinator and removes that tedious bit. This is a good thing because removing/reducing complexity is the primary reason we make functions
First, let's derive our very own Y-combinator
// standard definition
const Y = f => f (Y (f))
// prevent immediate infinite recursion in applicative order language (JS)
const Y = f => f (x => Y (f) (x))
// remove reference to self using U combinator
const Y = U (h => f => f (x => U (h) (f) (x)))
Now we will see how it's usage compares to the U-combinator. Notice, to recur, instead of U (f) we can simply call f ()
const U = f => f (f)
const Y = U (h => f => f (x => U (h) (f) (x)))
Y (f => (console.log ('stack overflow imminent!'), f ()))
Now I'll demonstrate the countDown program using Y – you'll see the programs are almost identical but the Y combinator keeps things a bit cleaner
const log = x => (console.log (x), x)
const U = f => f (f)
const Y = U (h => f => f (x => U (h) (f) (x)))
const countDown = Y (f => x => x > 0 ? f (log (x - 1)) : 0)
countDown (5)
// 4 3 2 1 0
countDown (3)
// 2 1 0
And now we'll see factorial as well
const U = f => f (f)
const Y = U (h => f => f (x => U (h) (f) (x)))
const factorial = Y (f => x =>
x === 0 ? 1 : x * f (x - 1))
console.log (factorial (5)) // 120
As you can see, f becomes the mechanism for recursion itself. To recur, we call it like an ordinary function. We can call it multiple times with different arguments and the result will still be correct. And since it's an ordinary function parameter, we can name it whatever we like, such as recur below -
const U = f => f (f)
const Y = U (h => f => f (x => U (h) (f) (x)))
const fibonacci = Y (recur => n =>
n < 2 ? n : recur (n - 1) + (n - 2))
console.log (fibonacci (10)) // 55
U and Y combinator with more than 1 parameter
In the examples above, we saw how we can loop and pass an argument to keep track of the "state" of our computation. But what if we need to keep track of additional state?
We could use compound data like an Array or something...
const U = f => f (f)
const Y = U (h => f => f (x => U (h) (f) (x)))
const fibonacci = Y (f => ([a, b, x]) =>
x === 0 ? a : f ([b, a + b, x - 1]))
// starting with 0 and 1, generate the 7th number in the sequence
console.log (fibonacci ([0, 1, 7]))
// 0 1 1 2 3 5 8 13
But this is bad because it's exposing internal state (counters a and b). It would be nice if we could just call fibonacci (7) to get the answer we want.
Using what we know about curried functions (sequences of unary (1-paramter) functions), we can achieve our goal easily without having to modify our definition of Y or rely upon compound data or advanced language features.
Look at the definition of fibonacci closely below. We're immediately applying 0 and 1 which are bound to a and b respectively. Now fibonacci is simply waiting for the last argument to be supplied which will be bound to x. When we recurse, we must call f (a) (b) (x) (not f (a,b,x)) because our function is in curried form.
const U = f => f (f)
const Y = U (h => f => f (x => U (h) (f) (x)))
const fibonacci = Y (f => a => b => x =>
x === 0 ? a : f (b) (a + b) (x - 1)) (0) (1)
console.log (fibonacci (7))
// 0 1 1 2 3 5 8 13
This sort of pattern can be useful for defining all sorts of functions. Below we'll see two more functions defined using the Y combinator (range and reduce) and a derivative of reduce, map.
const U = f => f (f)
const Y = U (h => f => f (x => U (h) (f) (x)))
const range = Y (f => acc => min => max =>
min > max ? acc : f ([...acc, min]) (min + 1) (max)) ([])
const reduce = Y (f => g => y => ([x,...xs]) =>
x === undefined ? y : f (g) (g (y) (x)) (xs))
const map = f =>
reduce (ys => x => [...ys, f (x)]) ([])
const add = x => y => x + y
const sq = x => x * x
console.log (range (-2) (2))
// [ -2, -1, 0, 1, 2 ]
console.log (reduce (add) (0) ([1,2,3,4]))
// 10
console.log (map (sq) ([1,2,3,4]))
// [ 1, 4, 9, 16 ]
IT'S ALL ANONYMOUS OMG
Because we're working with pure functions here, we can substitute any named function for its definition. Watch what happens when we take fibonacci and replace named functions with their expressions
/* const U = f => f (f)
*
* const Y = U (h => f => f (x => U (h) (f) (x)))
*
* const fibonacci = Y (f => a => b => x => x === 0 ? a : f (b) (a + b) (x - 1)) (0) (1)
*
*/
/*
* given fibonacci (7)
*
* replace fibonacci with its definition
* Y (f => a => b => x => x === 0 ? a : f (b) (a + b) (x - 1)) (0) (1) (7)
*
* replace Y with its definition
* U (h => f => f (x => U (h) (f) (x))) (f => a => b => x => x === 0 ? a : f (b) (a + b) (x - 1)) (0) (1) (7)
//
* replace U with its definition
* (f => f (f)) U (h => f => f (x => U (h) (f) (x))) (f => a => b => x => x === 0 ? a : f (b) (a + b) (x - 1)) (0) (1) (7)
*/
let result =
(f => f (f)) (h => f => f (x => h (h) (f) (x))) (f => a => b => x => x === 0 ? a : f (b) (a + b) (x - 1)) (0) (1) (7)
console.log (result) // 13
And there you have it – fibonacci (7) calculated recursively using nothing but anonymous functions
It may be simplest to use an "anonymous object" instead:
({
do: function() {
console.log("don't run this ...");
this.do();
}
}).do();
Your global space is completely unpolluted. It's pretty straightforward. And you can easily take advantage of the object's non-global state.
You can also use ES6 object methods to make the syntax more concise.
({
do() {
console.log("don't run this ...");
this.do();
}
}).do();
I would not do this as an inline function. It's pushing against the boundaries of good taste and doesn't really get you anything.
If you really must, there is arguments.callee as in Fabrizio's answer. However this is generally considered inadvisable and is disallowed in ECMAScript Fifth Edition's ‘strict mode’. Although ECMA 3 and non-strict-mode are not going away, working in strict mode promises more possible language optimisations.
One can also use a named inline function:
(function foo(data){
data++;
var nothing = function() {
foo(data);
}
nothing();
})();
However named inline function expressions are also best avoided, as IE's JScript does some bad things to them. In the above example foo incorrectly pollutes the parent scope in IE, and the parent foo is a separate instance to the foo seen inside foo.
What's the purpose of putting this in an inline anonymous function? If you just want to avoid polluting the parent scope, you can of course hide your first example inside another self-calling-anonymous-function (namespace). Do you really need to create a new copy of nothing each time around the recursion? You might be better off with a namespace containing two simple mutually-recursive functions.
(function(data){
var recursive = arguments.callee;
data = data+1;
var nothing = function() {
recursive(data)
}
nothing();
})();
You could do something like:
(foo = function() { foo(); })()
or in your case:
(recur = function(data){
data = data+1;
var nothing = function() {
if (data > 100) return; // put recursion limit
recur(data);
}
nothing();
})(/* put data init value here */ 0);
When you declare an anonymous function like this:
(function () {
// Pass
}());
Its considered a function expression and it has an optional name (that you can use to call it from within itself. But because it's a function expression (and not a statement) it stays anonymous (but has a name that you can call). So this function can call itself:
(function foo () {
foo();
}());
foo //-> undefined
Why not pass the function to the functio itself ?
var functionCaller = function(thisCaller, data) {
data = data + 1;
var nothing = function() {
thisCaller(thisCaller, data);
};
nothing();
};
functionCaller(functionCaller, data);
In certain situations you have to rely on anonymous functions. Given is a recursive map function:
const map = f => acc => ([head, ...tail]) => head === undefined
? acc
: map (f) ([...acc, f(head)]) (tail);
const sqr = x => x * x;
const xs = [1,2,3,4,5];
console.log(map(sqr) ([0]) (xs)); // [0] modifies the structure of the array
Please note that map must not modify the structure of the array. So the accumulator acc needn't to be exposed. We can wrap map into another function for instance:
const map = f => xs => {
let next = acc => ([head, ...tail]) => head === undefined
? acc
: map ([...acc, f(head)]) (tail);
return next([])(xs);
}
But this solution is quite verbose. Let's use the underestimated U combinator:
const U = f => f(f);
const map = f => U(h => acc => ([head, ...tail]) => head === undefined
? acc
: h(h)([...acc, f(head)])(tail))([]);
const sqr = x => x * x;
const xs = [1,2,3,4,5];
console.log(map(sqr) (xs));
Concise, isn't it? U is dead simple but has the disadvantage that the recursive call gets a bit obfuscated: sum(...) becomes h(h)(...) - that's all.
I am not sure if the answer is still required but this can also be done using delegates created using function.bind:
var x = ((function () {
return this.bind(this, arguments[0])();
}).bind(function (n) {
if (n != 1) {
return n * this.bind(this, (n - 1))();
}
else {
return 1;
}
}))(5);
console.log(x);
This does not involve named functions or arguments.callee.
With ES2015 we can play around a bit with the syntax and abuse default parameters and thunks. The latter are just functions without any arguments:
const applyT = thunk => thunk();
const fib = n => applyT(
(f = (x, y, n) => n === 0 ? x : f(y, x + y, n - 1)) => f(0, 1, n)
);
console.log(fib(10)); // 55
// Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55...
Please note that f is a parameter with the anonymous function (x, y, n) => n === 0 ? x : f(y, x + y, n - 1) as its default value. When f is invoked by applyT this invocation must take place without arguments, so that the default value is used. The default value is a function and hence f is a named function, which can call itself recursively.
Like bobince wrote, simply name your function.
But, I'm guessing you also want to pass in an initial value and stop your function eventually!
var initialValue = ...
(function recurse(data){
data++;
var nothing = function() {
recurse(data);
}
if ( ... stop condition ... )
{ ... display result, etc. ... }
else
nothing();
}(initialValue));
working jsFiddle example (uses data += data for fun)
i needed (or rather, wanted) an one-liner anonymous function to walk its way up an object building up a string, and handled it like this:
var cmTitle = 'Root' + (function cmCatRecurse(cmCat){return (cmCat == root) ? '' : cmCatRecurse(cmCat.parent) + ' : ' + cmCat.getDisplayName();})(cmCurrentCat);
which produces a string like 'Root : foo : bar : baz : ...'
Another answer which does not involve named function or arguments.callee
var sum = (function(foo,n){
return n + foo(foo,n-1);
})(function(foo,n){
if(n>1){
return n + foo(foo,n-1)
}else{
return n;
}
},5); //function takes two argument one is function and another is 5
console.log(sum) //output : 15
This is a rework of jforjs answer with different names and a slightly modified entry.
// function takes two argument: first is recursive function and second is input
var sum = (function(capturedRecurser,n){
return capturedRecurser(capturedRecurser, n);
})(function(thisFunction,n){
if(n>1){
return n + thisFunction(thisFunction,n-1)
}else{
return n;
}
},5);
console.log(sum) //output : 15
There was no need to unroll the first recursion. The function receiving itself as a reference harkens back to the primordial ooze of OOP.
This is a version of #zem's answer with arrow functions.
You can use the U or the Y combinator. Y combinator being the simplest to use.
U combinator, with this you have to keep passing the function:
const U = f => f(f)
U(selfFn => arg => selfFn(selfFn)('to infinity and beyond'))
Y combinator, with this you don't have to keep passing the function:
const Y = gen => U(f => gen((...args) => f(f)(...args)))
Y(selfFn => arg => selfFn('to infinity and beyond'))
Yet another Y-combinator solution, using rosetta-code link (I think somebody previously mentioned the link somewhere on stackOverflow.
Arrows are for anonymous functions more readable to me:
var Y = f => (x => x(x))(y => f(x => y(y)(x)));
I don't suggest doing this in any practical use-case, but just as a fun exercise, you can actually do this using a second anonymous function!
(f => f(f))(f => {
data = data+1;
var nothing = function() {
f();
}
nothing(f);
});
The way this works is that we're passing the anonymous function as an argument to itself, so we can call it from itself.
by using arguments.callee(). For more details visit this url: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#scope_and_the_function_stack
(function(data){
data = data+1;
var nothing = function() {
arguments.callee() // this calls the function itself
}
nothing();
})();
This may not work everywhere, but you can use arguments.callee to refer to the current function.
So, factorial could be done thus:
var fac = function(x) {
if (x == 1) return x;
else return x * arguments.callee(x-1);
}

Categories

Resources