Function composition using point-free style creates a very concise and readable code:
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 * 2
const h = compose( trace('after f'), // 'after f: 42' f, trace('after g'), // 'after g: 21' g) // function application order is from bottom to top
h(20) // => 42Compose can be a fantastic, utility, but a more convenient way of reading code is top-to-bottom:
const trace = (label) => (value) => { console.log(`${label}: ${value}`) return value}
const g = (n) => n + 1const f = (n) => n * 2
const 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 bottom
h(20) // => 42Currying can be a useful abstraction to specialized functions:
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:
const g = (n) => n + 1const f = (n) => n * 2
const 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) // => 42Data 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.