I try to implement a Functor in JavaScript.
A diagram of definition to the Functor is as follows:
or in nLab
https://ncatlab.org/nlab/show/functor
Here, as you see F(f)
expression looks typical in category diagrams.
I managed to implement Array.map
as a Functor in JavaScript as follows:
const compose = f => g => x => g(f(x));
const f = a => a * 2;
const F = a => [a];
const A = 1;
const FA = F(A); //[1]
const Ff = compose(f)(F);
const FB = Ff([FA]);
console.log(FB); //[2]
F = a => [a]
when A = 1
,
F(1) = [1]
However, although I understand what F(f)
means,
F(f) = [f]
won't work as a function in JavaScript, at least. .
In fact, only what I can think of an adequate way is function composition such as:
compose(f)(F)
.
Also, I did
FB = Ff([FA])
to make it work, however, I think this expression smartly works only for array, and in other cases, things go wrong.
So, here is my question.
Although I understand what F(A)
, F(B)
, and F(B)
suggests, and in fact, F(A)
, F(B)
works, doesn't F(f)
have to be composition of the functions not direct apply?
Or, in category theory, does it allow to express function composition of f
and g
as just g(f)
implicitly??
The functor implementation for a JavaScript array is Array.map
, which takes a function on array elements and produces a function on arrays. If f
is some function then, in terms of your diagrams' categorical language, F(f)
is .map(f)
(please excuse my abuse of notation).
In the diagrams, the identities and composition are not meant to show how the functor abstraction should be implemented. Rather, what the diagrams are expressing are the functor laws: in concrete terms, that .map(id)
must be the same as id
, and that .map(f).map(g)
must be the same as .map(compose(f)(g))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With