JavaScript Currying 4 - Trace

September 17, 2020

Function composition using point-free style creates a very concise and readable code:

1const trace = (label) => (value) => {
2 console.log(`${label}: ${value}`)
3 return value
4}
5
6const compose = (...functions) => (x) =>
7 functions.reduceRight((y, f) => f(y), x)
8
9const g = (n) => n + 1
10const f = (n) => n * 2
11
12const h = compose(
13 trace('after f'), // 'after f: 42'
14 f,
15 trace('after g'), // 'after g: 21'
16 g
17) // function application order is from bottom to top
18
19h(20) // => 42

Compose can be a fantastic, utility, but a more convenient way of reading code is top-to-bottom:

1const trace = (label) => (value) => {
2 console.log(`${label}: ${value}`)
3 return value
4}
5
6const g = (n) => n + 1
7const f = (n) => n * 2
8
9const pipe = (...functions) => (x) => functions.reduce((y, f) => f(y), x)
10
11// updated usage
12const h = pipe(
13 g,
14 trace('after g'), // 'after g: 21'
15 f,
16 trace('after f') // 'after f: 42'
17) // function application order is from top to bottom
18
19h(20) // => 42

Currying can be a useful abstraction to specialized functions:

1const map = (fn) => (mappable) => mappable.map(fn)
2const double = (n) => n * 2
3const doubleAll = map(double)
4doubleAll([1, 2, 3]) // => [2, 4, 6]

If the trace function were not curried, it would look like this:

1const g = (n) => n + 1
2const f = (n) => n * 2
3
4const pipe = (...functions) => (x) => functions.reduce((y, f) => f(y), x)
5
6const trace = (label, value) => {
7 console.log(`${label}: ${value}`)
8 return value
9}
10
11const h = pipe(
12 g,
13 (x) => trace('after g', x), // 'after g: 21'
14 f,
15 (x) => trace('after f', x) // 'after f: 42'
16)
17
18h(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.