Search code examples
javascripthaskellfunctorcategory-theory

Functor implementation in JavaScript


I try to implement a Functor in JavaScript.

A diagram of definition to the Functor is as follows:

enter image description here

or in nLab

enter image description here

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??


Solution

  • After I had many answers here and was not satisfied with them, I've resolved by myself.

    In terms of the diagram in nLab:

    enter image description here

    Here, X,Y,Z is identity morphism in fact.

    So the Type of X,Y,Z and f,g,h is identical.

    Therefore, we can write F(f) or F(X) consistently.

    According to this QA process, although many have never mentioned and also disagreed to my initial response, this seems to be a known fact.

    https://mathoverflow.net/questions/336533/why-is-an-object-not-defined-as-identity-morphism

    https://ncatlab.org/nlab/show/single-sorted+definition+of+a+category

    From the perspective of single-sorted definition of category, the object, X,Y,Z is identity morphism.