Published
Edited
Oct 26, 2018
1 star
Insert cell
Insert cell
function printResult() {
// This is how to use the `sumFactory` manually.
// The param passed to `finalSum` is the last tail (eg. [3]),
// that's why we don't need to provide any sum function to it,
// because it will never be used.
const finalSum = sumFactory(/*no need any other sum here*/);
const anotherSum = sumFactory(finalSum);
const sum1 = sumFactory(anotherSum);
console.log(sum1([1,2,3])) // -> 6
// This is using Y combinator to make the `sumFactory`
// become a function that can be run automatically
const sum2 = Y(sumFactory)
return sum2(arrayOfNumber);
}
Insert cell
function Y(f) {
return (
// In JS, we can not omit the argument `a`,
// since JS is not lazy evaluation by default,
// hence it will cause stack overflow. This version
// of Y combinator is called Z combinator.
// It's ok to omit `a` is language that supports
// lazy evaluation, like Haskell
m => a => f(m(m))(a) // This line can be replaced with `x => x(x)`
)(
m => a => f(m(m))(a)
);
}
Insert cell
function sumFactory (sum) {
return function (arr) {
const [head, ...tail] = arr;
if (tail.length === 0) return head;
return head + sum(tail);
}
}

Insert cell
arrayOfNumber = [1,2,3,4,5,6,7]
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more