JavaScript Currying 4 - Trace
September 17, 2020Function composition using point-free style creates a very concise and readable code:
index.js
const trace = (label) => (value) => {console.log(`${label}: ${value}`)return value}const compose =(...functions) =>(x) =>functions.reduceRight((y, f) => f(y), x)const g = (n) => n + 1const f = (n) => n * 2const h = compose(trace('after f'), // 'after f: 42'f,trace('after g'), // 'after g: 21'g) // function application order is from bottom to toph(20) // => 42
Compose can be a fantastic, utility, but a more convenient way of reading code is top-to-bottom:
index.js
const trace = (label) => (value) => {console.log(`${label}: ${value}`)return value}const g = (n) => n + 1const f = (n) => n * 2const pipe =(...functions) =>(x) =>functions.reduce((y, f) => f(y), x)// updated usageconst h = pipe(g,trace('after g'), // 'after g: 21'f,trace('after f') // 'after f: 42') // function application order is from top to bottomh(20) // => 42
Currying can be a useful abstraction to specialized functions:
index.js
const map = (fn) => (mappable) => mappable.map(fn)const double = (n) => n * 2const doubleAll = map(double)doubleAll([1, 2, 3]) // => [2, 4, 6]
If the trace
function were not curried, it would look like this:
index.js
const g = (n) => n + 1const f = (n) => n * 2const pipe =(...functions) =>(x) =>functions.reduce((y, f) => f(y), x)const trace = (label, value) => {console.log(`${label}: ${value}`)return value}const h = pipe(g,(x) => trace('after g', x), // 'after g: 21'f,(x) => trace('after f', x) // 'after f: 42')h(20) // => 42
Data the last style means that function should take the specializing parameters first and take the data later.
The arguments which have been applied to partially applied function are called fixed parameters.
Point-free style is a way of defining function without reference to its arguments. Point free function is created by calling a function that returns a function such as a curried function.