Does functional programming have a standard construct for this logic?
const passAround = (f) => (x) => {
f(x);
return x;
};
This enables me to compose functions that have side effects and no return values, like console.log
. It's not like a Task because I don't want to represent the state of the side effect.
The SKI combinator calculus might interest you. Let's pretend that
f
is always a pure function:Anyway, the reason why I bring up the SKI combinator calculus is because I want to introduce you to the concept of Applicative Functors. In particular, the
Reader
applicative functor is equivalent to the SKI combinator calculus. TheS
combinator is equivalent to theap
method ofReader
and theK
combinator is equivalent to thepure
method ofReader
.In JavaScript, the equivalent of
Reader
isFunction
. Hence, we can defineap
andpure
for functions in JavaScript as follows:But wait, there's so much more that you can do with applicative functors. Every applicative functor is also a functor. This means that applicative functors must also have a
map
method. ForReader
themap
method is just function composition. It's equivalent to theB
combinator. Usingmap
you can do really interesting things like:The
seq
function is in fact equivalent to the(*>)
method of the Applicative class. This enables a functional style of method cascading.