Suppose you have an array of numbers xs
:
[10, 5, 12, 7]
You need to transform it in two ways:
xs.map(x => x % 2 == 0 ? x + 1 : x + 2);
//=> [11, 7, 13, 9]
xs.map(x => x % 2 == 0 ? x + 10 : x + 20);
//=> [20, 25, 22, 27]
I'll quickly acknowledge that the ternary expressions are probably just fine but for the purpose of answering the question I'll make them pointfree:
const ifelse = (p, t, f) => x => p(x) ? t(x) : f(x);
const add = a => x => a + x;
const even = x => x % 2 == 0;
xs.map(ifelse(even, add(1), add(2)));
//=> [11, 7, 13, 9]
xs.map(ifelse(even, add(10), add(20)));
//=> [20, 25, 22, 27]
Now let's say that we just want to return 'even'
or 'odd'
:
xs.map(ifelse(even, () => 'even', () => 'odd'));
//=> ['even', 'odd', 'even', 'odd']
The two lambdas behave in the same way: they completely ignore x
and always return the same value. This is exactly what the Kestrel combinator is about:
const K = a => x => a;
xs.map(ifelse(even, K('even'), K('odd')));
//=> ['even', 'odd', 'even', 'odd']