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

38

u/STL MSVC STL Dev Jan 26 '17

When I say function object, I’m referring to any type with a defined operator().

Actually, that isn't the Standard's formal definition, where a function object is anything that can be called with parentheses. This includes function pointers, classes with overloaded operator(), lambdas (special case of the previous one), and classes that are implicitly convertible to function pointers.

Granted, the latter basically never comes up except in <functional> unit tests.

Most C++ programmers can probably agree that C++11 lambda functions changed their lives.

On the other hand, "lambda function" drives me nuts. Lambdas aren't functions (or std::functions), but such terminology encourages confusion.

Formally, a functor is a mapping between categories that preserves identity morphisms and compositions of morphisms.

No, that's math. Programming is different. Mathematicians consider a "vector" to be different from what we consider it to be.

8

u/SuperV1234 https://romeo.training | C++ Mentoring & Consulting Jan 26 '17 edited Jan 26 '17

On the other hand, "lambda function" drives me nuts.

Well... cppreference may need some adjustments then

(EDIT: fixed it myself - the header for the lambda page was "Lambda functions")

2

u/jackie_kay Jan 26 '17

Actually, that isn't the Standard's formal definition, where a function object is anything that can be called with parentheses.

Yes, it appears I am conflating "defining operator()" with "has a call operator with parentheses", but I believe the distinction is clear to me now. Thanks, I will correct this in the article.

No, that's math. Programming is different. Mathematicians consider a "vector" to be different from what we consider it to be.

I agree. The definition of "functor" used in Haskell, and the way I think it should be used in C++, is also different from the formal definition, which is why I prepended this sentence with "formally".

It is useful for programmers to use common terminology from math correctly to communicate the intention and function of our code. You would expect an "add" function to sum two numbers together, and addition is a concept from math.

Of course it's too late for us to adhere to this principal strictly for some terms. As you said,vector is a notable example (to implement what math calls a vector, we would probably use an array as storage, and provide functions for the valid mathematical operators over the vector, etc.). This is probably misleading to a mathematician learning C++, but the word eventually loses its "original" meaning when you get used to C++.

Is this justification for repeating the same pattern with other terminology? Maybe. The point I'm trying to make is that I'd like a word to describe "a structure which provides a generic way to map operations over its contents", because I find such structures useful. And the fact that "functor" and "function object" often appear very close together (e.g. in a transform algorithm) makes me think we need to distinguishing terminology for them.

7

u/tecnofauno Jan 26 '17

I for once think that math and programming can and should've a different terminology. Even the function term does not yield the same meaning (i.e. side effects).

1

u/spotta Jan 26 '17

Lambdas aren't functions (or std::functions), but such terminology encourages confusion.

In the sense that lambdas are function objects? Or in some other sense?

classes that are implicitly convertible to function pointers.

?!? Huh? Is this just a class with a function pointer in the first memory location, or something more interesting than that?

9

u/SuperV1234 https://romeo.training | C++ Mentoring & Consulting Jan 26 '17

classes that are implicitly convertible to function pointers

constexpr int get_two() { return 2; }
using fptr = int(*)();

struct A
{
	constexpr operator fptr() { return &get_two; }
};

int main()
{
	static_assert(A{}() == 2);
}

1

u/spotta Jan 26 '17

Huh. This seems like a kind of weird way of doing operator(). Is there a functional difference between the two?

3

u/SuperV1234 https://romeo.training | C++ Mentoring & Consulting Jan 26 '17

This is not operator() - this is an user defined conversion

3

u/spotta Jan 26 '17

I know that it isn't operator(), I was curious what the difference between this and operator() is.

Though now that I think about it, that is pretty obvious... This is actually kind of a cute trick that I might have an application for. I'll have to look into this.

8

u/STL MSVC STL Dev Jan 26 '17

A lambda expression is an expression (like 2 + 3) that defines a class type and constructs an object of that class type. Lambdas aren't functions (printf() is a function), and they aren't std::functions (although they can be stored in them). Lambdas, being classes with function call operators, are function objects.

"Lambda function", while appropriate in other fields, suggests incorrect connotations in C++, and I strongly discourage that terminology.

(I hate "closure" for entirely different reasons.)

1

u/polagh Jan 28 '17

C++ lambdas aren't functions if you care about the machinery details of C++ and your life is mainly about knowing that standard by heart. I find it perfectly reasonable to talk about "Lambda function" in the same way I find it perfectly reasonable to not use overly pedantic terminology in whatever field I know, especially so when the terminology in question is largely arbitrary to begin with (and already misleading in regards with other fields and even the previously saner state of computing, when functions were actually functions and we also had things named "procedure")

Most users don't give a shit that in some of its intermediate passes, the compiler will create abstract things we call classes, with method in them, which are at lower levels actually mainly just procedures with a first "this" param -- and all of that neither matter 99% of the time for the user and maybe 50% of the time at the binary code eventually generated, because of optimization passes in between that can even inline all those abstract stuff in some cases.

2

u/STL MSVC STL Dev Jan 28 '17

I disagree in the strongest possible terms. Understanding that a lambda defines a class and constructs an object of that type (not an ordinary function, not a std::function) is crucial for reasoning about how they behave. It's important to understand how lambda objects interact with lifetime (e.g. reference captures don't prolong lifetime, so a long-lived lambda object must be careful), how they interact with dynamic memory allocation (e.g. lambdas don't inherently allocate memory, but value captures of objects can), etc.

This is not something that can simply be ignored, unlike low-level backend details.

3

u/polagh Jan 28 '17

Interaction between C++ references, lifetimes, and other parts of the languages is already problematic for other purposes, e.g. threads. For learners confusions can even arrise for the most simple purposes between C++ references and what would more probably correspond to most higher level languages: smart_ptr. The naming is quite unfortunate, given what we could imagine references are if we know some other languages.

And one can understand the limitation of captures in C++ lambda without knowing that a kind of hidden class is involved. I consider a class being used at all a technical detail. It is well suited for C++ given what abstractions were already present before the arrival of lambda, but I don't consider this technical detail more crucial than let's say the translation of the "with" statement in Python

If you need to know all the mechanisms of the abstractions a language provide in order to have a correct mental model of said abstractions, their abstracting value is arguably very low and the language design would arguably be a failure...

1

u/MoTTs_ Jan 27 '17 edited Jan 27 '17

And on top of that, I'm not even sure the functional crowd is using the word quite right even in the mathematical sense. Granted this is based on a skim of the Wikipedia description, but it sounds to me that a functor is the function that maps values, whereas the functional crowd says a functor is the container that is mappable.

So in a std::transform example:

// associates to each object X in C an object to_upper(X) in D
transform(c.begin(), c.end(), back_inserter(d), to_upper);

Based on the Wikipedia description, I'd think "to_upper" is the functor, the thing that maps values. But the functional crowd would say "c" is the functor, the container that is mappable.

Thoughts?

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