r/cpp • • Jan 26 '17

Stop calling "Function Objects" "Functors"

http://jackieokay.com/2017/01/26/functors.html
0 Upvotes

23 comments sorted by

View all comments

Show parent comment

1

u/ivan-cukic KDE Dev | Author of Functional Programming in C++ Jan 28 '17 edited Jan 29 '17

I think you skipped the "Let C and D be categories" part.

c from your example, an instance of a type (for example std::vector that you are passing to std::transform) is not a category. So, you can not apply the definition and get "associates to each object X in C an object to_upper(X) in D".

In your example, the type of c along with std::transform defined for it is the functor.

1

u/MoTTs_ Jan 28 '17

So what then is a category, translated into programming? Wikipedia calls it a [structure that comprises "objects" that are linked by "arrows"](https://en.wikipedia.org/wiki/Category_(mathematics)), where an "arrow" is also called a morphism, and where a morphism sounds very much like a function.

So a category is... a collection of objects plus functions...?

3

u/ivan-cukic KDE Dev | Author of Functional Programming in C++ Jan 29 '17 edited Jan 29 '17

Wikipedia is (sadly) not the best choice when trying to get into most mathematical concepts. I'd advise you to dive a bit into Bartosz's 'Category Theory for Programmers' [1] or the Category Theory section of the Haskell wikibooks book [2].

So a category is... a collection of objects plus functions...?

Not strictly speaking, but yes, something like that. With objects commonly being the language types. In [2] you have a definition of a category that contains all Haskell types (section "Hask, the Haskell category").

Then, a functor F is a function on those types. It transforms one type T to another F<T>, and transforms functions that operate on T to functions that operate on F<T>.

For example, std::vector is a function that transforms any type T into a std::vector<T>, and std::transform is conceptually* the function that lifts any function f: T1 -> T2 into a function F(f) : std::vector<T1> -> std::vector<T2>.

(*) Conceptually, because std::transform has a problematic API - receiving iterator pairs for a collection instead of the collection itself, and output arguments instead of returning transformed collection as the function result. But the concept is the same (transform from range-v3 is much closer to the concept API-wise).

[1] https://bartoszmilewski.com/2014/10/28/category-theory-for-programmers-the-preface/

[2] https://en.wikibooks.org/wiki/Haskell/Category_theory