How are functors useful?

I know this is a late reply, but I thought I add some advantages about functors I did not see mentioned in this thread.

I have implemented various algorithms in both approaches. Sometimes I have some struct which must be passed in to select correct algorithm and parameters, while other times I use a functor.

Say you use the non-functor approach. Your calls would be something like f(a, x) where a is a parameter used by the algorithm and x is the input. With a functor it is is more like f = F(a); f(x). The benefit of the former is that sometimes you want multiple operations operating on the same structure. E.g. one encryption and one decryption algorithm. In this case functors are not much of an advantage I suppose.

However the benefit of being able to call a function like f(x) where x is the input is because function composition tends to be a lot easier to accomplish with single argument function. Or function composition at least benefits from function only taking inputs and not parameters controlling the operations of the algorithm. It makes it easier to chain function calls with |>, to use them with map, broadcast, filter etc.

Functions which only take inputs and not parameters are more compatible with various libraries. It provides a more universal interface. It is a bit like Unix pipelines. The power comes form a simple standardised universal interface that a lot of programs can adhere to.

12 Likes