JavaScript Currying 4 - Trace
September 17, 2020Function composition using point-free style creates a very concise and readable code:
index.js
1const trace = (label) => (value) => {2 console.log(`${label}: ${value}`)3 return value4}56const compose =7 (...functions) =>8 (x) =>9 functions.reduceRight((y, f) => f(y), x)1011const g = (n) => n + 112const f = (n) => n * 21314const h = compose(15 trace('after f'), // 'after f: 42'16 f,17 trace('after g'), // 'after g: 21'18 g19) // function application order is from bottom to top2021h(20) // => 42
Compose can be a fantastic, utility, but a more convenient way of reading code is top-to-bottom:
index.js
1const trace = (label) => (value) => {2 console.log(`${label}: ${value}`)3 return value4}56const g = (n) => n + 17const f = (n) => n * 289const pipe =10 (...functions) =>11 (x) =>12 functions.reduce((y, f) => f(y), x)1314// updated usage15const h = pipe(16 g,17 trace('after g'), // 'after g: 21'18 f,19 trace('after f') // 'after f: 42'20) // function application order is from top to bottom2122h(20) // => 42
Currying can be a useful abstraction to specialized functions:
index.js
1const map = (fn) => (mappable) => mappable.map(fn)2const double = (n) => n * 23const doubleAll = map(double)4doubleAll([1, 2, 3]) // => [2, 4, 6]
If the trace
function were not curried, it would look like this:
index.js
1const g = (n) => n + 12const f = (n) => n * 234const pipe =5 (...functions) =>6 (x) =>7 functions.reduce((y, f) => f(y), x)89const trace = (label, value) => {10 console.log(`${label}: ${value}`)11 return value12}1314const h = pipe(15 g,16 (x) => trace('after g', x), // 'after g: 21'17 f,18 (x) => trace('after f', x) // 'after f: 42'19)2021h(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.