Search code examples
javascriptfunctormap-function

Is JavaScript Array.map generally an endofunctor or just a functor?


  1. A functor is a structure-preserving transformation between categories. It's some way to map objects from one category to objects of another category while also preserving the arrows between objects—think of it as a category homomorphism.

  2. An endofunctor is a functor from one category back to the same category.

In JavaScript, Array.map can be generally chained because it always returns Array.

someArray
.map(f1) 
.map(f2) 
.map(f3)
...

So, at the first time, considering (2), I simply thought "ok, since Array is a special type that has a method map, and it returns the same type, JavaScript array must be endofunctor."

However, considering (1), I thought "wait, is it just a structure saving feature of all functors that is not limited to endofunctor?"

In other words, is it safe to say "if it is chainable, it is an endofunctor"? Or it's invalid since chainable map and endo- is another concept?


Solution

  • Yes, Array.map is endofunctor in javascript, as it returns object by using object as self. Notice, only in JS, as it use simply object.

    In other lang like C#, when you define an array you need to give type of containning, mapping between them become functor but not endofunctor.

    It is easy to identify. If and only if a functor of class always return the same class as itself, this functor is an endofunctor.

    Thus in a class MyClass,

    a: function(){
       return this;
    },
    b: function(){
       return new MyClass();
    }
    

    Those are endofunctor.

    However, it is not safe to say a chain-able functor is endofunctor.

    Simply imagine two class, class MyClassA() and class MyClassB(), both have a functor sharing same name (this is usual).

    In MyClassA,

    changetype: function(){
       return MyClassB;
    }
    

    and vice versa.

    So, once you can write something like

    a = new MyClassA();
    a.changetype().changetype().changetype()......
    

    and have no trouble.

    So if you find a functor chain-able, you cannot determine if it is an endofunctor.As sharing same name functor is very very typical in all programming language.