The use cases of constant
only become clear to you if you understand the functional paradigm. With functional programming, literally everything can be expressed with functions. Constants are no exception. Here is a contrived example:
const map = f => xs =>
xs.map(f);
const co = x => y => x;
console.log(
map(co(0)) ([1,2,3]) // [0,0,0]
);
Let's implement a more complex example. We want a function that takes two monadic computations (aka actions), but we are only interested in the result of the second action. So why do we need the first action in the first place? Because we are interested in its side effect:
const chain = mx =>
fm => x => fm(mx(x)) (x);
const co = x => y => x;
const seq = mx => my =>
chain(mx) (co(my));
const sqr = n =>
n * n;
// monadic sequence
const z = seq(console.log) (sqr);
// apply it
const r = z(5); // logging 5 is the observed effect
console.log("return value:", r); // logs the return value 25
Usually a composition with console.log
would lead to an error: add(console.log(5)) (5)
yields NaN
. But our actual composition looks like add(co(sqr) (console.log(5)) (5)
and yields 25
as desired.
However, as I mentioned above, to understand advanced functional idioms that take advantage of constant
you need a proper understanding of the paradigm.