So what is functor?
A functor is a container of type a that, when subjected to a function that maps from a→b, yields a container of type b.
https://stackoverflow.com/a/2031430/2706861
In functional programming, a functor is a design pattern inspired by the definition from category theory, that allows for a generic type to apply a function inside without changing the structure of the generic type.
Wikipedia
…and endfunctor?
Endofunctor: A functor that maps a category to that same category; e.g., polynomial functor.
Wikipedia
Okay, and where are functors and endfunctors in Javascript? For example:
- Array has functor(endfunctor) method map:
[1, 2, 3].map((num) => num.toString())
Array containing a Number(Array<Number>) is mapped to Array<String> using map method. It maps from one category(Array) to the same category(Array). Such functor is called endfunctor.
- Promise has functor (endfunctor) method then:
Promise.resolve(1).then((v) => ({v: v.toString()}))
Promise containing a Number (Promise<Number>) is mapped to Promise<{v: String}> using then method. It maps from one category(Promise) to the same category(Promise). Method then is also an endfunctor. (v) => ({v: v.toString()}) is a mapping function.
References:
https://blog.ploeh.dk/2018/03/22/functors/
Leave a Reply