How to conditionally assign to a variable in functional way? - javascript

I need to assign a value to a variable based on condition. I want to do it with a functional programming paradigm in mind, thus I cannot declare it in outer scope and then reassign.
// let foo = undefined // no-let!
if(condition) {
const foo = 1
} else {
const foo = 0
}
do_some_stuff(foo) // Uncaught ReferenceError: foo is not defined
I know, I can use ternary expression here like
const foo = condition ? 1 : 0
but what if I have some other routine to do inside my condition, like:
if(condition) {
const foo = 1
do_stuff()
} else {
const foo = 0
do_other_stuff()
}
do_third_stuff(foo)

Probably you would encode your case using some algebraic data type (ADT) like Either. That is, you may cover two subcases: left and right.
See the code from // --> Solution starts here onwards. Previous code is a mini standard FP library using vanilla JavaScript to make the code runnable. Check it and enjoy!
// Mini standard library
// -------------------------------
// The identity combinator
// I :: a -> a
const I = x => x
// Either ADT
const Either = (() => {
// Creates an instance of Either.Right
//
// of :: b -> Either a b
const of = x => ({ right: x })
// Creates an instance of Either.Right
//
// Right :: b -> Either a b
const Right = of
// Creates an instance of Either.Left
//
// Left :: a -> Either a b
const Left = x => ({ left: x })
// Maps Either.Left or Either.Right in a single operation
//
// bimap :: (a -> c) -> (b -> d) -> Either a b -> Either c -> d
const bimap = f => g => ({ left, right }) => left ? Left (f (left)) : Right (g (right))
// Lifts a value to Either based on a condition, where false
// results in Left, and true is Right.
//
// tagBy :: (a -> Boolean) -> a -> Either a a
const tagBy = f => x => f (x) ? Right (x) : Left (x)
// Unwraps Either.Left or Either.Right with mapping functions
//
// either :: (a -> c) -> (b -> c) -> Either a b -> c
const either = f => g => ({ left, right }) => left ? f (left) : g (right)
// Unwraps Either.Left or Either.Right and outputs the raw value on them
//
// unwrap :: Either a b -> c
const unwrap = either (I) (I)
return { of, Right, Left, bimap, tagBy, either, unwrap }
}) ()
// --> Solution starts here
// Lifts to Either.Right if x is greater than 3,
// otherwise, x is encoded as Left.
//
// tagGt3 :: Number -> Either Number Number
const tagGt3 = Either.tagBy (x => x > 3)
// doStuff :: Number -> Number
const doStuff = x => x + 1
// doStuff2 :: Number -> Number
const doStuff2 = x => x * 4
// doStuff3 :: Either Number Number -> Either Number Number
const doStuff3 = Either.bimap (doStuff) (doStuff2) // <-- here's the decision!
const eitherValue1 = doStuff3 (tagGt3 (2))
const eitherValue2 = doStuff3 (tagGt3 (30))
const output1 = Either.unwrap (eitherValue1)
const output2 = Either.unwrap (eitherValue2)
console.log ('output1: ', output1)
console.log ('output2: ', output2)
Refactor using pipes
Now I introduce pipe to glue a composition of one or more unary functions, which makes the code more elegant:
// Mini standard library
// -------------------------------
// The identity combinator
// I :: a -> a
const I = x => x
// Pipes many unary functions
//
// pipe :: [a -> b] -> a -> c
const pipe = xs => x => xs.reduce ((o, f) => f (o), x)
// Either ADT
const Either = (() => {
// Creates an instance of Either.Right
//
// of :: b -> Either a b
const of = x => ({ right: x })
// Creates an instance of Either.Right
//
// Right :: b -> Either a b
const Right = of
// Creates an instance of Either.Left
//
// Left :: a -> Either a b
const Left = x => ({ left: x })
// Maps Either.Left or Either.Right in a single operation
//
// bimap :: (a -> c) -> (b -> d) -> Either a b -> Either c -> d
const bimap = f => g => ({ left, right }) => left ? Left (f (left)) : Right (g (right))
// Lifts a value to Either based on a condition, where false
// results in Left, and true is Right.
//
// tagBy :: (a -> Boolean) -> a -> Either a a
const tagBy = f => x => f (x) ? Right (x) : Left (x)
// Unwraps Either.Left or Either.Right with mapping functions
//
// either :: (a -> c) -> (b -> c) -> Either a b -> c
const either = f => g => ({ left, right }) => left ? f (left) : g (right)
// Unwraps Either.Left or Either.Right and outputs the raw value on them
//
// unwrap :: Either a b -> c
const unwrap = either (I) (I)
return { of, Right, Left, bimap, tagBy, either, unwrap }
}) ()
// --> Solution starts here
// doStuff :: Number -> Number
const doStuff = x => x + 1
// doStuff2 :: Number -> Number
const doStuff2 = x => x * 4
const { tagBy, bimap, unwrap } = Either
// doStuff3 :: Number -> Number
const doStuff3 = pipe ([
tagBy (x => x > 3),
bimap (doStuff) (doStuff2), // <-- here's the decision!
unwrap
])
const output1 = doStuff3 (2)
const output2 = doStuff3 (30)
console.log ('output1: ', output1)
console.log ('output2: ', output2)

Nothing is stopping you from splitting the two:
const foo = condition ? 1 : 0;
if(condition) {
do_stuff();
} else {
do_other_stuff();
}
do_third_stuff(foo);
In case condition is an expensive execution, simply assign it to a variable before using it multiple times:
let isFoo = expensiveIsFooMethod();
const foo = isFoo ? 1 : 0;
if(isFoo) {
do_stuff();
} else {
do_other_stuff();
}
do_third_stuff(foo);
You're right that it would be cleaner if you didn't have to repeat the condition, but you've introduced this limitation because you're using a const variable which makes it impossible to assign a value to your const in more than one place.
I suggest outweighing the two options here. What matters to you more: cleaner syntax, or ensuring you'll never overwrite the value?

Because you dont want to declare foo outside, why you do not simply this way:
if(condition) {
const foo = 1
do_stuff()
do_third_stuff(foo)
} else {
const foo = 0
do_other_stuff()
do_third_stuff(foo)
}

Related

Sanctuary Js and Defining a Contravariant Functor

I am trying this from scratch learning about Contravariants and deeper knowledge of Sanctuary. The code "works" but again I don't have the types exactly right.
Here is the Contravariant
const {contramap: contramapFl, extract } = require('fantasy-land');
const getInstance = (self, constructor) =>
(self instanceof constructor) ?
self :
Object.create(constructor.prototype) ;
// Contra a ~> g: a -> ?
const Contra = function(g){
const self = getInstance(this, Contra)
// :: F a ~> b -> a -> F b [ b -> a -> ? ]
self[contramapFl] = f => Contra( x => g(f(x)) )
self[extract] = g
self['##type'] = 'fs-javascript/contra'
return Object.freeze(self)
}
// UPDATE adding type to constructor
Contra['##type'] = 'fs-javascript/contra'
And my attempt to get the types right
const $ = require('sanctuary-def');
const type = require('sanctuary-type-identifiers');
const Z = require('sanctuary-type-classes') ;
const isContra = x => type (x) === 'fs-javascript/contra'
const ContraType = $.UnaryType(
'fs-javascript/contra',
'http://example.com/fs-javascript#Contra',
isContra,
x => [x[extract]])($.Unknown)
Then my test
const {create, env} = require('sanctuary');
const {contramap} = create({checkTypes: true, env: env.concat(ContraType) });
const isEven = Contra(x => x % 2 === 0) ;
console.log(Z.Contravariant.test(isEven)) // => true
const isLengthEvenContra = contramap(y => y.length, isEven)
const isStringLengthEven = isLengthEvenContra[extract]
console.log(isStringLengthEven("asw")) //=> ERROR
TypeError: Type-variable constraint violation
contramap :: Contravariant f => (b -> a) -> f a -> f b
^
1
1) "fs-javascript/contra" :: String
f => Contra( x => g(f(x)) ) :: Function, (c -> d)
x => x % 2 === 0 :: Function, (c -> d)
Since there is no type of which all the above values are members, the type-variable constraint has been violated.
If I disable the type checking then it works as expected, so logically it appears to be stitched together properly. I defined my own version of contramap
const def = $.create({ checkTypes: true, env: $.env.concat(ContraType) });
const contramap2 =
def('contramap2', {}, [$.Unknown, ContraType, ContraType],
(f, x) => {
const z = x[contramapFl](f)
return z
}
)
I then rerun the test:
const isEven = Contra(x => x % 2 === 0) ;
console.log(Z.Contravariant.test(isEven)) // => true
const isLengthEvenContra = contramap2(y => y.length, isEven)
const isStringLengthEven = isLengthEvenContra[extract]
console.log(isStringLengthEven("asw")) //=> false
So withstanding the discussion as to whether the contravaiant functor is the best approach to this problem (learning exercise), the question is how, when defining my own implementation of a contravariant, can I use sanctuary's contramap function with the type checking enabled.
after updating by adding the code:
Contra['##type'] = 'fs-javascript/contra'
changed the error to:
TypeError: Type-variable constraint violation
contramap :: Contravariant f => (b -> a) -> f a -> f b
^ ^
1 2
1) 3 :: Number, FiniteNumber, NonZeroFiniteNumber, Integer, NonNegativeInteger, ValidNumber
2) x => x % 2 === 0 :: Function, (c -> d)
Since there is no type of which all the above values are members, the type-variable constraint has been violated.
// Contra (Integer -> Boolean)
const isEven = Contra(x => x % 2 === 0) ;
// String -> Integer
const strLength = y => y.length
// I Think: Contra (String -> (Integer -> Boolean))
const isLengthEvenContra = contramap(strLength, isEven)
// (String -> (Integer -> Boolean))
const isStringLengthEven = isLengthEvenContra[extract]
My understanding of the contravariant functor was that it pre-composed the function within it, with the function passed in via contramap. So if the contravariant contained the function f and it is contramap with g it returns a new contravariant functor wrapping x = g(f(x)) Have i misunderstood this (too)
Here's the boilerplate for defining a custom type and including it in the Sanctuary environment:
'use strict';
const {create, env} = require ('sanctuary');
const $ = require ('sanctuary-def');
const type = require ('sanctuary-type-identifiers');
// FooType :: Type -> Type
const FooType = $.UnaryType
('my-package/Foo')
('https://my-package.org/Foo')
(x => type (x) === 'my-package/Foo#1')
(foo => []);
// foo :: Foo
const foo = {
'constructor': {'##type': 'my-package/Foo#1'},
'fantasy-land/contramap': function(f) {
throw new Error ('Not implemented');
},
};
const S = create ({
checkTypes: true,
env: env.concat ([FooType ($.Unknown)]),
});
S.I (foo);
// => foo
S.contramap (S.I) (foo);
// ! Error: Not implemented
You're composing functions. Sanctuary defines fantasy-land/map and fantasy-land/contramap for Function a b, so there's no need for a Contra wrapping type.
> S.map (S.even) (s => s.length) ('Sanctuary')
false
> S.contramap (s => s.length) (S.even) ('Sanctuary')
false

Function that will execute function depending on value. Functional programming

I have two functions and they are executed depending of if statement. E.g.:
if(value) {
doA()
} else {
doB()
}
How to write function or object that will take the result and decide whether or not execute each function. I want to receive something like this:
exists(result).doA()
nothing(result).doB()
I want to learn some functional programming in JavaScrit so I woud appreciate any source from which I can learn FP in JavaScript.
continuation passing style
here's an approach using continuation passing style. you'll notice the implementation of main is not far off from your original encoding –
once you finish wrapping your head around this, if you haven't already learned about monads, you now know the best one (cont) ^_^
// cont :: a -> (a -> b) -> b
const cont = x =>
k => k (x)
// when :: (a -> boolean, a -> b, a -> b) -> a -> (a -> b) -> b
const when = (f,l,r) => x =>
f (x) ? cont (l (x)) : cont (r (x))
// isOdd :: number -> boolean
const isOdd = x =>
x & 1 === 1
// doA :: number -> number
const doA = x =>
x + 1
// doB :: number -> number
const doB = x =>
x * x
// main :: number -> void
const main = x =>
cont (x) (when (isOdd, doA, doB)) (console.log)
main (3) // IO: 4, doA (3) === 3 + 1
main (4) // IO: 16, doB (4) === 4 * 4
data constructors
here's another approach using simple data constructors Left and Right to represent a Fork sum type – this results in a sort of data-directed style where the control of main is determined by the input type
// type Fork a = Left a | Right a
// Left a :: { fork :: (a -> b, _) -> b }
const Left = x =>
({ type: Left, fork: (f,_) => f (x) })
// Right a :: { fork :: (_, a -> b) -> b }
const Right = x =>
({ type: Right, fork: (_,f) => f (x) })
// doA :: number -> number
const doA = x =>
x + 1
// doB :: number -> number
const doB = x =>
x * x
// main :: Fork a -> a
const main = f =>
// fork applies the left function (doA) to a Left
// fork applies the right function (doB) to a Right
f.fork (doA, doB)
console.log (main (Left (3))) // => 4, doA (3) === 3 + 1
console.log (main (Right (3))) // => 9, doB (3) === 3 * 3
You could write something like this, for example:
function exists(value) {
return function (func) {
if (value !== undefined) {
return func(value);
}
return null;
}
}
function nothing(value) {
return function (func) {
if (value === undefined) {
return func();
}
return null;
}
}
function doA(value) {
console.log('doing A', value);
}
function doB() {
console.log('doing B');
}
const foo = 'fool';
const bar = undefined;
exists(foo)(doA);
nothing(bar)(doB);
The exists function gets a value and returns another function. The function that is returned gets yet another function as argument, which is executed if the value passed is defined.
I've used “old school” anonymous functions in the example above to make it easier to understand. With ES6 arrow functions, you can write the exists and nothing functions more consisely, like this:
function exists(value) {
return func => value !== undefined ? func(value) : null;
}
function nothing(value) {
return func => value === undefined ? func(value) : null;
}
The “functional programming fun” really starts when you realize you can refactor these two functions by putting the common code in another function, that is then used to create the two functions, like this:
function executeWithCondition(predicate) {
return value => func => predicate(value) ? func(value) : null;
}
const exists = executeWithCondition(value => value !== undefined);
const nothing = executeWithCondition(value => value === undefined);
This technique is called currying.
Usage of these functions is still the same:
exists(foo)(doA);
nothing(bar)(doB);
Here's the complete runnable code example:
function executeWithCondition(predicate) {
return value => func => predicate(value) ? func(value) : null;
}
const exists = executeWithCondition(value => value !== undefined);
const nothing = executeWithCondition(value => value === undefined);
function doA(value) {
console.log('doing A', value);
}
function doB() {
console.log('doing B');
}
const foo = 'fool';
const bar = undefined;
exists(foo)(doA);
nothing(bar)(doB);
One approach would be to define the properties of an object with values set to functions
const o = {
exists: function(value) {
return value ? this.doA() : this.doB()
},
doA: function(value) {
console.log("A")
},
doB: function(value) {
console.log("B")
}
}
o.exists(void 0);

How do I replace while loops with a functional programming alternative without tail call optimization?

I am experimenting with a more functional style in my JavaScript; therefore, I have replaced for loops with utility functions such as map and reduce. However, I have not found a functional replacement for while loops since tail call optimization is generally not available for JavaScript. (From what I understand ES6 prevents tail calls from overflowing the stack but does not optimize their performance.)
I explain what I have tried below, but the TLDR is:
If I don't have tail call optimization, what is the functional way to implement while loops?
What I have tried:
Creating a "while" utility function:
function while(func, test, data) {
const newData = func(data);
if(test(newData)) {
return newData;
} else {
return while(func, test, newData);
}
}
Since tail call optimization isn't available I could rewrite this as:
function while(func, test, data) {
let newData = *copy the data somehow*
while(test(newData)) {
newData = func(newData);
}
return newData;
}
However at this point it feels like I have made my code more complicated/confusing for anyone else who uses it, since I have to lug around a custom utility function. The only practical advantage that I see is that it forces me to make the loop pure; but it seems like it would be more straightforward to just use a regular while loop and make sure that I keep everything pure.
I also tried to figure out a way to create a generator function that mimics the effects of recursion/looping and then iterate over it using a utility function like find or reduce. However, I haven't figured out an readable way to do that yet.
Finally, replacing for loops with utility functions makes it more apparent what I am trying to accomplish (e.g. do a thing to each element, check if each element passes a test, etc.). However, it seems to me that a while loop already expresses what I am trying to accomplish (e.g. iterate until we find a prime number, iterate until the answer is sufficiently optimized, etc.).
So after all this, my overall question is: If I need a while loop, I am programming in a functional style, and I don't have access to tail call optimization, then what is the best strategy.
An example in JavaScript
Here's an example using JavaScript. Currently, most browsers do not support tail call optimisation and therefore the following snippet will fail
const repeat = n => f => x =>
n === 0 ? x : repeat (n - 1) (f) (f(x))
console.log(repeat(1e3) (x => x + 1) (0)) // 1000
console.log(repeat(1e5) (x => x + 1) (0)) // Error: Uncaught RangeError: Maximum call stack size exceeded
Trampolines
We can work around this limitation by changing the way we write repeat, but only slightly. Instead of returning a value directly or immediately recurring, we will return one of our two trampoline types, Bounce or Done. Then we will use our trampoline function to handle the loop.
// trampoline
const Bounce = (f,x) => ({ isBounce: true, f, x })
const Done = x => ({ isBounce: false, x })
const trampoline = ({ isBounce, f, x }) => {
while (isBounce)
({ isBounce, f, x } = f(x))
return x
}
// our revised repeat function, now stack-safe
const repeat = n => f => x =>
n === 0 ? Done(x) : Bounce(repeat (n - 1) (f), f(x))
// apply trampoline to the result of an ordinary call repeat
let result = trampoline(repeat(1e6) (x => x + 1) (0))
// no more stack overflow
console.log(result) // 1000000
Currying slows things down a little bit too, but we can remedy that using an auxiliary function for the recursion. This is nice too because it hides the trampoline implementation detail and does not expect the caller to bounce the return value. This runs about twice as fast as the above repeat
// aux helper hides trampoline implementation detail
// runs about 2x as fast
const repeat = n => f => x => {
const aux = (n, x) =>
n === 0 ? Done(x) : Bounce(x => aux (n - 1, x), f (x))
return trampoline (aux (n, x))
}
Clojure-style loop/recur
Trampolines are nice and all but it's kind of annoying to have to have to worry about calling trampoline on your function's return value. We saw the alternative was to use an auxiliary helper, but c'mon that's kind of annoying, too. I'm sure some of you aren't too keen about the Bounce and Done wrappers, too.
Clojure creates a specialised trampoline interface that uses a pair of functions, loop and recur – this tandem pair lends itself to a remarkably elegant expression of a program
Oh and it's really fast, too
const recur = (...values) =>
({ recur, values })
const loop = run =>
{ let r = run ()
while (r && r.recur === recur)
r = run (...r.values)
return r
}
const repeat = n => f => x =>
loop
( (m = n, r = x) =>
m === 0
? r
: recur (m - 1, f (r))
)
console.time ('loop/recur')
console.log (repeat (1e6) (x => x + 1) (0)) // 1000000
console.timeEnd ('loop/recur') // 24 ms
Initially this style will feel foreign, but over time I am finding it to be the most consistent while producing durable programs. Comments below help ease you into the expression-rich syntax -
const repeat = n => f => x =>
loop // begin a loop with
( ( m = n // local loop var m: counter, init with n
, r = x // local loop var r: result, init with x
) =>
m === 0 // terminating condition
? r // return result
: recur // otherwise recur with
( m - 1 // next m value
, f (r) // next r value
)
)
The continuation monad
This is one of my favourite topics tho, so we're gonna see what this looks like with the continuation monad. Reusing loop and recur, we implement a stack-safe cont that can sequence operations using chain and run operation sequences using runCont. For repeat, this is senseless (and slow), but it's cool to see the mechanics of cont at work in this simple example -
const identity = x =>
x
const recur = (...values) =>
({ recur, values })
const loop = run =>
{ let r = run ()
while (r && r.recur === recur)
r = run (...r.values)
return r
}
// cont : 'a -> 'a cont
const cont = x =>
k => recur (k, x)
// chain : ('a -> 'b cont) -> 'a cont -> 'b cont
const chain = f => mx =>
k => recur (mx, x => recur (f (x), k))
// runCont : ('a -> 'b) -> a cont -> 'b
const runCont = f => mx =>
loop ((r = mx, k = f) => r (k))
const repeat = n => f => x =>
{ const aux = n => x =>
n === 0 // terminating condition
? cont (x) // base case, continue with x
: chain // otherise
(aux (n - 1)) // sequence next operation on
(cont (f (x))) // continuation of f(x)
return runCont // run continuation
(identity) // identity; pass-thru
(aux (n) (x)) // the continuation returned by aux
}
console.time ('cont monad')
console.log (repeat (1e6) (x => x + 1) (0)) // 1000000
console.timeEnd ('cont monad') // 451 ms
Y combinator
The Y combinator is my spirit combinator; this answer would be incomplete without giving it some place amongst the other techniques. Most implementations of the Y combinator however, are not stack-safe and will overflow if the user-supplied function recurs too many times. Since this answer is all about preserving stack-safe behaviour, of course we'll implement Y in a safe way – again, relying on our trusty trampoline.
Y demonstrates the ability to extend easy-to-use, stack-safe, synchronous infinite recursion without cluttering up your function.
const bounce = f => (...xs) =>
({ isBounce: true, f, xs })
const trampoline = t => {
while (t && t.isBounce)
t = t.f(...t.xs)
return t
}
// stack-safe Y combinator
const Y = f => {
const safeY = f =>
bounce((...xs) => f (safeY (f), ...xs))
return (...xs) =>
trampoline (safeY (f) (...xs))
}
// recur safely to your heart's content
const repeat = Y ((recur, n, f, x) =>
n === 0
? x
: recur (n - 1, f, f (x)))
console.log(repeat (1e5, x => x + 1, 0)) // 10000
Practicality with while loop
But let's be honest: that's a lot of ceremony when we're overlooking one of the more obvious potential solutions: use a for or while loop, but hide it behind a functional interface
For all intents and purposes, this repeat function works identically to the ones provided above – except this one is about one or two gadzillion times faster (with exception to the loop/recur solution). Heck, it's arguably a lot easier to read too.
Granted, this function is perhaps a contrived example – not all recursive functions can be converted to a for or while loop so easily, but in such a scenario where it's possible, it's probably best to just do it like this. Save the trampolines and continuations for heavy lifting when a simple loop won't do.
const repeat = n => f => x => {
let m = n
while (true) {
if (m === 0)
return x
else
(m = m - 1, x = f (x))
}
}
const gadzillionTimes = repeat(1e8)
const add1 = x => x + 1
const result = gadzillionTimes (add1) (0)
console.log(result) // 100000000
setTimeout is NOT a solution to the stack overflow problem
OK, so it does work, but only paradoxically. If your dataset is small, you don't need setTimeout because there will be no stack overflow. If your dataset is large and you use setTimeout as a safe recursion mechanism, not only do you make it impossible to synchronously return a value from your function, it will be so F slow you won't even want to use your function
Some people have found an interview Q&A prep site that encourages this dreadful strategy
What our repeat would look like using setTimeout – notice it's also defined in continuation passing style – ie, we must call repeat with a callback (k) to get the final value
// do NOT implement recursion using setTimeout
const repeat = n => f => x => k =>
n === 0
? k (x)
: setTimeout (x => repeat (n - 1) (f) (x) (k), 0, f (x))
// be patient, this one takes about 5 seconds, even for just 1000 recursions
repeat (1e3) (x => x + 1) (0) (console.log)
// comment the next line out for absolute madness
// 10,000 recursions will take ~1 MINUTE to complete
// paradoxically, direct recursion can compute this in a few milliseconds
// setTimeout is NOT a fix for the problem
// -----------------------------------------------------------------------------
// repeat (1e4) (x => x + 1) (0) (console.log)
I can't stress enough how bad this is. Even 1e5 takes so long to run that I gave up trying to measure it. I'm not including this in the benchmarks below because it's just too slow to even be considered a viable approach.
Promises
Promises have the ability to chain computations and are stack safe. However, achieving a stack-safe repeat using Promises means we'll have to give up our synchronous return value, the same way we did using setTimeout. I'm providing this as a "solution" because it does solve the problem, unlike setTimeout, but in a way that's very simple compared to the trampoline or continuation monad. As you might imagine though, the performance is somewhat bad, but nowhere near as bad as the setTimeout example above
Worth noting in this solution, the Promise implementation detail is completely hidden from the caller. A single continuation is provided as a 4th argument and its called when the computation is complete.
const repeat = n => f => x => k =>
n === 0
? Promise.resolve(x).then(k)
: Promise.resolve(f(x)).then(x => repeat (n - 1) (f) (x) (k))
// be patient ...
repeat (1e6) (x => x + 1) (0) (x => console.log('done', x))
Benchmarks
Seriously, the while loop is a lot faster - like almost 100x faster (when comparing best to worst – but not including async answers: setTimeout and Promise)
// sync
// -----------------------------------------------------------------------------
// repeat implemented with basic trampoline
console.time('A')
console.log(tramprepeat(1e6) (x => x + 1) (0))
console.timeEnd('A')
// 1000000
// A 114 ms
// repeat implemented with basic trampoline and aux helper
console.time('B')
console.log(auxrepeat(1e6) (x => x + 1) (0))
console.timeEnd('B')
// 1000000
// B 64 ms
// repeat implemented with cont monad
console.time('C')
console.log(contrepeat(1e6) (x => x + 1) (0))
console.timeEnd('C')
// 1000000
// C 33 ms
// repeat implemented with Y
console.time('Y')
console.log(yrepeat(1e6) (x => x + 1) (0))
console.timeEnd('Y')
// 1000000
// Y 544 ms
// repeat implemented with while loop
console.time('D')
console.log(whilerepeat(1e6) (x => x + 1) (0))
console.timeEnd('D')
// 1000000
// D 4 ms
// async
// -----------------------------------------------------------------------------
// repeat implemented with Promise
console.time('E')
promiserepeat(1e6) (x => x + 1) (0) (console.log)
console.timeEnd('E')
// 1000000
// E 2224 ms
// repeat implemented with setTimeout; FAILED
console.time('F')
timeoutrepeat(1e6) (x => x + 1) (0) (console.log)
console.timeEnd('F')
// ...
// too slow; didn't finish after 3 minutes
Stone Age JavaScript
The above techniques are demonstrated using newer ES6 syntaxes, but you could implement a trampoline in the earliest possible version of JavaScript – it only requires while and first class functions
Below, we use stone age javascript to demonstrate infinite recursion is possible and performant without necessarily sacrificing a synchronous return value – 100,000,000 recursions in under 6 seconds - this is a dramatic difference compared to setTimeout which can only 1,000 recursions in the same amount of time.
function trampoline (t) {
while (t && t.isBounce)
t = t.f (t.x);
return t.x;
}
function bounce (f, x) {
return { isBounce: true, f: f, x: x };
}
function done (x) {
return { isBounce: false, x: x };
}
function repeat (n, f, x) {
function aux (n, x) {
if (n === 0)
return done (x);
else
return bounce (function (x) { return aux (n - 1, x); }, f (x));
}
return trampoline (aux (n, x));
}
console.time('JS1 100K');
console.log (repeat (1e5, function (x) { return x + 1 }, 0));
console.timeEnd('JS1 100K');
// 100000
// JS1 100K: 15ms
console.time('JS1 100M');
console.log (repeat (1e8, function (x) { return x + 1 }, 0));
console.timeEnd('JS1 100M');
// 100000000
// JS1 100K: 5999ms
Non-blocking infinite recursion using stone age JavaScript
If, for some reason, you want non-blocking (asynchronous) infinite recursion, we can rely on setTimeout to defer a single frame at the start of the computation. This program also uses stone age javascript and computes 100,000,000 recursions in under 8 seconds, but this time in a non-blocking way.
This demonstrates that there's nothing special about having a non-blocking requirement. A while loop and first-class functions are still the only fundamental requirement to achieve stack-safe recursion without sacrificing performance
In a modern program, given Promises, we would substitute the setTimeout call for a single Promise.
function donek (k, x) {
return { isBounce: false, k: k, x: x };
}
function bouncek (f, x) {
return { isBounce: true, f: f, x: x };
}
function trampolinek (t) {
// setTimeout is called ONCE at the start of the computation
// NOT once per recursion
return setTimeout(function () {
while (t && t.isBounce) {
t = t.f (t.x);
}
return t.k (t.x);
}, 0);
}
// stack-safe infinite recursion, non-blocking, 100,000,000 recursions in under 8 seconds
// now repeatk expects a 4th-argument callback which is called with the asynchronously computed result
function repeatk (n, f, x, k) {
function aux (n, x) {
if (n === 0)
return donek (k, x);
else
return bouncek (function (x) { return aux (n - 1, x); }, f (x));
}
return trampolinek (aux (n, x));
}
console.log('non-blocking line 1')
console.time('non-blocking JS1')
repeatk (1e8, function (x) { return x + 1; }, 0, function (result) {
console.log('non-blocking line 3', result)
console.timeEnd('non-blocking JS1')
})
console.log('non-blocking line 2')
// non-blocking line 1
// non-blocking line 2
// [ synchronous program stops here ]
// [ below this line, asynchronous program continues ]
// non-blocking line 3 100000000
// non-blocking JS1: 7762ms
A better loop/recur pattern
There are two things that I dislike about the loop/recur pattern described in the accepted answer. Note that I actually like the idea behind the loop/recur pattern. However, I dislike the way it has been implemented. So, let's first look at the way I would have implemented it.
// Recur :: a -> Result a b
const Recur = (...args) => ({ recur: true, args });
// Return :: b -> Result a b
const Return = value => ({ recur: false, value });
// loop :: (a -> Result a b) -> a -> b
const loop = func => (...args) => {
let result = func(...args);
while (result.recur) result = func(...result.args);
return result.value;
};
// repeat :: (Int, a -> a, a) -> a
const repeat = loop((n, f, x) => n === 0 ? Return(x) : Recur(n - 1, f, f(x)));
console.time("loop/recur/return");
console.log(repeat(1e6, x => x + 1, 0));
console.timeEnd("loop/recur/return");
Compare this with the loop/recur pattern described in the aforementioned answer.
// recur :: a -> Recur a
const recur = (...args) => ({ recur, args });
// loop :: (a? -> Recur a ∪ b) -> b
const loop = func => {
let result = func();
while (result && result.recur === recur) result = func(...result.args);
return result;
};
// repeat :: (Int, a -> a, a) -> a
const repeat = (n, f, x) => loop((m = n, r = x) => m === 0 ? r : recur(m - 1, f(r)));
console.time("loop/recur");
console.log(repeat(1e6, x => x + 1, 0));
console.timeEnd("loop/recur");
If you notice, the type signature of the second loop function uses default parameters (i.e. a?) and untagged unions (i.e. Recur a ∪ b). Both of these features are at odds with the functional programming paradigm.
Problem with default parameters
The loop/recur pattern in the aforementioned answer uses default parameters to supply the initial arguments of the function. I think this is an abuse of default parameters. You can just as easily supply initial arguments using my version of loop.
// repeat :: (Int, a -> a, a) -> a
const repeat = (n, f, x) => loop((n, x) => n === 0 ? Return(x) : Recur(n - 1, f(x)))(n, x);
// or more readable
const repeat = (n, f, x) => {
const repeatF = loop((n, x) => n === 0 ? Return(x) : Recur(n - 1, f(x)));
return repeatF(n, x);
};
Futhermore, it allows eta conversion when the all the arguments are passed through.
// repeat :: (Int, a -> a, a) -> a
const repeat = (n, f, x) => loop((n, f, x) => n === 0 ? Return(x) : Recur(n - 1, f, f(x)))(n, f, x);
// can be η-converted to
const repeat = loop((n, f, x) => n === 0 ? Return(x) : Recur(n - 1, f, f(x)));
Using the version of loop with default parameters does not allow eta conversion. In addition, it forces you to rename parameters because you can't write (n = n, x = x) => ... in JavaScript.
Problem with untagged unions
Untagged unions are bad because they erase important information, i.e. information of where the data came from. For example, because my Result type is tagged I can distinguish Return(Recur(0)) from Recur(0).
On the other hand, because the right-hand side variant of Recur a ∪ b is untagged, if b is specialized to Recur a, i.e. if the type is specialized to Recur a ∪ Recur a, then it's impossible to determine whether the Recur a came from the left-hand side or the right-hand side.
One criticism might be that b will never be specialized to Recur a, and hence it doesn't matter that b is untagged. Here's a simple counterexample to that criticism.
// recur :: a -> Recur a
const recur = (...args) => ({ recur, args });
// loop :: (a? -> Recur a ∪ b) -> b
const loop = func => {
let result = func();
while (result && result.recur === recur) result = func(...result.args);
return result;
};
// repeat :: (Int, a -> a, a) -> a
const repeat = (n, f, x) => loop((m = n, r = x) => m === 0 ? r : recur(m - 1, f(r)));
// infinite loop
console.log(repeat(1, x => recur(1, x), "wow, such hack, much loop"));
// unreachable code
console.log("repeat wasn't hacked");
Compare this with my version of repeat which is bulletproof.
// Recur :: a -> Result a b
const Recur = (...args) => ({ recur: true, args });
// Return :: b -> Result a b
const Return = value => ({ recur: false, value });
// loop :: (a -> Result a b) -> a -> b
const loop = func => (...args) => {
let result = func(...args);
while (result.recur) result = func(...result.args);
return result.value;
};
// repeat :: (Int, a -> a, a) -> a
const repeat = loop((n, f, x) => n === 0 ? Return(x) : Recur(n - 1, f, f(x)));
// finite loop
console.log(repeat(1, x => Recur(1, x), "wow, such hack, much loop"));
// reachable code
console.log("repeat wasn't hacked");
Thus, untagged unions are unsafe. However, even if we were careful to avoid the pitfalls of untagged unions I would still prefer tagged unions because the tags provide useful information when reading and debugging the program. IMHO, the tags make the program more understandable and easier to debug.
Conclusion
To quote the Zen of Python.
Explicit is better than implicit.
Default parameters and untagged unions are bad because they are implicit, and can lead to ambiguities.
The Trampoline monad
Now, I'd like to switch gears and talk about monads. The accepted answer demonstrates a stack-safe continuation monad. However, if you only need to create a monadic stack-safe recursive function then you don't need the full power of the continuation monad. You can use the Trampoline monad.
The Trampoline monad is a more powerful cousin of the Loop monad, which is just the loop function converted into a monad. So, let's start by understanding the Loop monad. Then we'll see the main problem of the Loop monad and how the Trampoline monad can be used to fix that problem.
// Recur :: a -> Result a b
const Recur = (...args) => ({ recur: true, args });
// Return :: b -> Result a b
const Return = value => ({ recur: false, value });
// Loop :: (a -> Result a b) -> a -> Loop b
const Loop = func => (...args) => ({ func, args });
// runLoop :: Loop a -> a
const runLoop = ({ func, args }) => {
let result = func(...args);
while (result.recur) result = func(...result.args);
return result.value;
};
// pure :: a -> Loop a
const pure = Loop(Return);
// bind :: (Loop a, a -> Loop b) -> Loop b
const bind = (loop, next) => Loop(({ first, loop: { func, args } }) => {
const result = func(...args);
if (result.recur) return Recur({ first, loop: { func, args: result.args } });
if (first) return Recur({ first: false, loop: next(result.value) });
return result;
})({ first: true, loop });
// ack :: (Int, Int) -> Loop Int
const ack = (m, n) => {
if (m === 0) return pure(n + 1);
if (n === 0) return ack(m - 1, 1);
return bind(ack(m, n - 1), n => ack(m - 1, n));
};
console.log(runLoop(ack(3, 4)));
Note that loop has been split into a Loop and a runLoop function. The data structure returned by Loop is a monad, and the pure and bind functions implement its monadic interface. We use the pure and bind functions to write a straightforward implementation of the Ackermann function.
Unfortunately, the ack function is not stack safe because it recursively calls itself until it reaches a pure value. Instead, we would like ack to return a Recur like data structure for its inductive cases. However, Recur values are of type Result instead of Loop. This problem is solved by the Trampoline monad.
// Bounce :: (a -> Trampoline b) -> a -> Trampoline b
const Bounce = func => (...args) => ({ bounce: true, func, args });
// Return :: a -> Trampoline a
const Return = value => ({ bounce: false, value });
// trampoline :: Trampoline a -> a
const trampoline = result => {
while (result.bounce) result = result.func(...result.args);
return result.value;
};
// pure :: a -> Trampoline a
const pure = Return;
// bind :: (Trampoline a, a -> Trampoline b) -> Trampoline b
const bind = (first, next) => first.bounce ?
Bounce(args => bind(first.func(...args), next))(first.args) :
next(first.value);
// ack :: (Int, Int) -> Trampoline Int
const ack = Bounce((m, n) => {
if (m === 0) return pure(n + 1);
if (n === 0) return ack(m - 1, 1);
return bind(ack(m, n - 1), n => ack(m - 1, n));
});
console.log(trampoline(ack(3, 4)));
The Trampoline data type is a combination of Loop and Result. The Loop and Recur data constructors have been combined into a single Bounce data constructor. The runLoop function has been simplified and renamed to trampoline. The pure and bind functions have also been simplified. In fact, pure is just Return. Finally, we apply Bounce to the original implementation of the ack function.
Another advantage of Trampoline is that it can be used to define stack-safe mutually recursive functions. For example, here's an implementation of the Hofstadter Female and Male sequence functions.
// Bounce :: (a -> Trampoline b) -> a -> Trampoline b
const Bounce = func => (...args) => ({ bounce: true, func, args });
// Return :: a -> Trampoline a
const Return = value => ({ bounce: false, value });
// trampoline :: Trampoline a -> a
const trampoline = result => {
while (result.bounce) result = result.func(...result.args);
return result.value;
};
// pure :: a -> Trampoline a
const pure = Return;
// bind :: (Trampoline a, a -> Trampoline b) -> Trampoline b
const bind = (first, next) => first.bounce ?
Bounce(args => bind(first.func(...args), next))(first.args) :
next(first.value);
// female :: Int -> Trampoline Int
const female = Bounce(n => n === 0 ? pure(1) :
bind(female(n - 1), f =>
bind(male(f), m =>
pure(n - m))));
// male :: Int -> Trampoline Int
const male = Bounce(n => n === 0 ? pure(0) :
bind(male(n - 1), m =>
bind(female(m), f =>
pure(n - f))));
console.log(Array.from({ length: 21 }, (_, n) => trampoline(female(n))).join(" "));
console.log(Array.from({ length: 21 }, (_, n) => trampoline(male(n))).join(" "));
The major pain point of writing monadic code is callback hell. However, this can be solved using generators.
// Bounce :: (a -> Trampoline b) -> a -> Trampoline b
const Bounce = func => (...args) => ({ bounce: true, func, args });
// Return :: a -> Trampoline a
const Return = value => ({ bounce: false, value });
// trampoline :: Trampoline a -> a
const trampoline = result => {
while (result.bounce) result = result.func(...result.args);
return result.value;
};
// pure :: a -> Trampoline a
const pure = Return;
// bind :: (Trampoline a, a -> Trampoline b) -> Trampoline b
const bind = (first, next) => first.bounce ?
Bounce(args => bind(first.func(...args), next))(first.args) :
next(first.value);
// bounce :: (a -> Generator (Trampoline b)) -> a -> Trampoline b
const bounce = func => Bounce((...args) => {
const gen = func(...args);
const next = data => {
const { value, done } = gen.next(data);
return done ? value : bind(value, next);
};
return next(undefined);
});
// female :: Int -> Trampoline Int
const female = bounce(function* (n) {
return pure(n ? n - (yield male(yield female(n - 1))) : 1);
});
// male :: Int -> Trampoline Int
const male = bounce(function* (n) {
return pure(n ? n - (yield female(yield male(n - 1))) : 0);
});
console.log(Array.from({ length: 21 }, (_, n) => trampoline(female(n))).join(" "));
console.log(Array.from({ length: 21 }, (_, n) => trampoline(male(n))).join(" "));
Finally, mutually recursive functions also demonstrate the advantage of having a separate trampoline function. It allows us to call a function returning a Trampoline value without actually running it. This allows us to build bigger Trampoline values, and then run the entire computation when required.
Conclusion
If you're want to write indirectly or mutually recursive stack-safe functions, or monadic stack-safe functions then use the Trampoline monad. If you want to write non-monadic directly recursive stack-safe functions then use the loop/recur/return pattern.
Programming in the sense of the functional paradigm means that we are guided by types to express our algorithms.
To transform a tail recursive function into a stack-safe version we have to consider two cases:
base case
recursive case
We have to make a choice and this goes well with tagged unions. However, Javascript doesn't have such a data type so either we have to create one or fall back to Object encodings.
Object Encoded
// simulate a tagged union with two Object types
const Loop = x =>
({value: x, done: false});
const Done = x =>
({value: x, done: true});
// trampoline
const tailRec = f => (...args) => {
let step = Loop(args);
do {
step = f(Loop, Done, step.value);
} while (!step.done);
return step.value;
};
// stack-safe function
const repeat = n => f => x =>
tailRec((Loop, Done, [m, y]) => m === 0
? Done(y)
: Loop([m - 1, f(y)])) (n, x);
// run...
const inc = n =>
n + 1;
console.time();
console.log(repeat(1e6) (inc) (0));
console.timeEnd();
Function Encoded
Alternatively, we can create a real tagged union with a function encoding. Now our style is much closer to mature functional languages:
// type/data constructor
const Type = Tcons => (tag, Dcons) => {
const t = new Tcons();
t.run = cases => Dcons(cases);
t.tag = tag;
return t;
};
// tagged union specific for the case
const Step = Type(function Step() {});
const Done = x =>
Step("Done", cases => cases.Done(x));
const Loop = args =>
Step("Loop", cases => cases.Loop(args));
// trampoline
const tailRec = f => (...args) => {
let step = Loop(args);
do {
step = f(step);
} while (step.tag === "Loop");
return step.run({Done: id});
};
// stack-safe function
const repeat = n => f => x =>
tailRec(step => step.run({
Loop: ([m, y]) => m === 0 ? Done(y) : Loop([m - 1, f(y)]),
Done: y => Done(y)
})) (n, x);
// run...
const inc = n => n + 1;
const id = x => x;
console.log(repeat(1e6) (inc) (0));
See also unfold which (from Ramda docs)
Builds a list from a seed value. Accepts an iterator function, which
returns either false to stop iteration or an array of length 2
containing the value to add to the resulting list and the seed to be
used in the next call to the iterator function.
var r = n => f => x => x > n ? false : [x, f(x)];
var repeatUntilGreaterThan = n => f => R.unfold(r(n)(f), 1);
console.log(repeatUntilGreaterThan(10)(x => x + 1));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.22.1/ramda.min.js"></script>
I've been thinking about this question a lot. Recently I came across the need for a functional while loop.
It seems to me like the only thing this question really wants is a way to inline a while loop. There IS a way to do that using a closure.
"some string "+(a=>{
while(comparison){
// run code
}
return result;
})(somearray)+" some more"
Alternatively, if what you want is something that chains off an array, than you can use the reduce method.
somearray.reduce((r,o,i,a)=>{
while(comparison){
// run code
}
a.splice(1); // This would ensure only one call.
return result;
},[])+" some more"
None of this actually turns our while loop at its core into a function. But it does allow us the use of an inline loop. And I just wanted to share this with anyone who this might help.

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.

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