JavaScript Currying 4 - Trace

September 17, 2020

Function 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 value
4}
5
6const compose =
7 (...functions) =>
8 (x) =>
9 functions.reduceRight((y, f) => f(y), x)
10
11const g = (n) => n + 1
12const f = (n) => n * 2
13
14const h = compose(
15 trace('after f'), // 'after f: 42'
16 f,
17 trace('after g'), // 'after g: 21'
18 g
19) // function application order is from bottom to top
20
21h(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 value
4}
5
6const g = (n) => n + 1
7const f = (n) => n * 2
8
9const pipe =
10 (...functions) =>
11 (x) =>
12 functions.reduce((y, f) => f(y), x)
13
14// updated usage
15const 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 bottom
21
22h(20) // => 42

Currying can be a useful abstraction to specialized functions:

index.js
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:

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

Share this post on Twitter