# How are functors useful?

**URL:** <https://discourse.julialang.org/t/how-are-functors-useful/24110>\
**Category:** New to Julia\
**Tags:** functors\
**Created:** [May 11, 2019, 2:46pm UTC](https://discourse.julialang.org/t/how-are-functors-useful/24110 "2019-05-11T14:46:27Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![tk3369](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tk3369/32/2824_2.png) [@tk3369](https://discourse.julialang.org/u/tk3369)\
**Post date:** [May 11, 2019, 2:46pm UTC](https://discourse.julialang.org/t/how-are-functors-useful/24110/1 "2019-05-11T14:46:27Z")

</div>

It’s interesting that a method can be defined and attached to a type as described in the [documentation about functors](https://docs.julialang.org/en/v1/manual/methods/#Function-like-objects-1).

I’m curious how it is ever useful though. Why not just define a regular function so it has a name that describes the intention of the logic? Using a functor is like an anonymous function but the implementation is “hidden”…

---

<div class="post-metadata">

**Author:** ![mohamed82008](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mohamed82008/32/18171_2.png) [@mohamed82008](https://discourse.julialang.org/u/mohamed82008)\
**Post date:** [May 11, 2019, 2:50pm UTC](https://discourse.julialang.org/t/how-are-functors-useful/24110/2 "2019-05-11T14:50:53Z")

</div>

I use it to define algorithm structs that are callable. The type wraps the parameters and pre-allocated memory needed by the algorithm. It is then called with the inputs of the algorithm as arguments and returns the outputs. It is just a nice way to pre-allocate and define parameters then “call” the algorithm.

---

<div class="post-metadata">

**Author:** ![tk3369](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tk3369/32/2824_2.png) [@tk3369](https://discourse.julialang.org/u/tk3369)\
**Post date:** [May 11, 2019, 2:56pm UTC](https://discourse.julialang.org/t/how-are-functors-useful/24110/3 "2019-05-11T14:56:47Z")

</div>

Doesn’t that constrain yourself to have 1 algorithm per struct? Why not define a struct, pre-allocate via constructor, and write a function for each algorithm?

Perhaps this is an “inside-out” thinking. The algorithm is the main thing but you want to use some data structure only inside this algorithm. Since we cannot define structs inside functions, using functors would be the only way to achieve that. Right?

---

<div class="post-metadata">

**Author:** ![mohamed82008](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mohamed82008/32/18171_2.png) [@mohamed82008](https://discourse.julialang.org/u/mohamed82008)\
**Post date:** [May 11, 2019, 3:19pm UTC](https://discourse.julialang.org/t/how-are-functors-useful/24110/4 "2019-05-11T15:19:10Z")

</div>

Well, I think you can achieve the same thing with a function, just pre-allocate separately in a non-callable struct and then pass it to a function with the name of the algorithm, but why have 2 separate entities when they can be combined? It’s just a mental model and API thing rather than an absolute necessity, for me at least.

An algorithm struct can also be composed of other sub-algorithms with different parameters and pre-allocated data structures, where the subalgs are called during the call of the main alg. So it is just a nice way to organize the code for me.

---

<div class="post-metadata">

**Author:** ![baggepinnen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/baggepinnen/32/693_2.png) [@baggepinnen](https://discourse.julialang.org/u/baggepinnen)\
**Post date:** [May 11, 2019, 3:40pm UTC](https://discourse.julialang.org/t/how-are-functors-useful/24110/5 "2019-05-11T15:40:58Z")

</div>

We use them to define objects called transfer functions. These represent functions in the mathematical sense as well and it becomes very logical to call them as such. The same would go for a polynomial type etc.

Flux does this to make their neural network layers behave like functions, same concept, very useful and intuitive.

---

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [May 11, 2019, 3:48pm UTC](https://discourse.julialang.org/t/how-are-functors-useful/24110/6 "2019-05-11T15:48:10Z")

</div>

With a function you can only do one thing, call it. With a functor you can define additional methods to expose other information and functionality, but still have the convenience of a function-call API.

For example, there are various packages (Polynomials, ApproxFun, etc.) that provide a data structure wrapping a polynomial `p`. It is natural to make these callable so that you can use the syntax `p(x)` to evaluate the polynomial, but that’s not _all_ you want to do with polynomials so you need a struct and not an anonymous function.

---

<div class="post-metadata">

**Author:** ![Raf](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/raf/32/3383_2.png) [@Raf](https://discourse.julialang.org/u/Raf)\
**Post date:** [May 11, 2019, 4:38pm UTC](https://discourse.julialang.org/t/how-are-functors-useful/24110/7 "2019-05-11T16:38:12Z")

</div>

I use this all the time. A simple example is for passing a loss function to Optim.jl that needs attached data and preallocated arrays.

I find it a lot clearer and more self contained to define a struct than to pass arguments in an anonymous function. I think Julia is doing the same thing with a closure anyway, you just cant use the `#XX` struct for anything else. With a functor you could print details about the model with `show(x)`, or whatever.

---

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [May 11, 2019, 5:32pm UTC](https://discourse.julialang.org/t/how-are-functors-useful/24110/8 "2019-05-11T17:32:02Z")

</div>

> [@Raf](#):
>
> for passing a loss function to Optim.jl that needs attached data and preallocated arrays.

For this purpose, I would tend to just use a closure. The distinction here is that Optim _only_ needs to call your function and can’t do anything else with the attached data, so there is no benefit to defining a callable struct … unless you are going to do other things with the object besides pass it to Optim.

---

<div class="post-metadata">

**Author:** ![tk3369](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tk3369/32/2824_2.png) [@tk3369](https://discourse.julialang.org/u/tk3369)\
**Post date:** [May 11, 2019, 5:55pm UTC](https://discourse.julialang.org/t/how-are-functors-useful/24110/9 "2019-05-11T17:55:29Z")

</div>

I see. It does seem quite natural to evaluate polynomials as `p(x)` rather than `evaluate(p, x)`. Looks cleaner and less verbose.

An additional thought - the lack of a function name seems to coincide with the common usage with an implicit name of _evaluate_, which works with polynomials, algorithms, Flux layers, etc. So the way that I could describe the action of “calling the struct” as “evaluating the struct for given arguments.”

---

<div class="post-metadata">

**Author:** ![TsurHerman](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tsurherman/32/1234_2.png) [@TsurHerman](https://discourse.julialang.org/u/TsurHerman)\
**Post date:** [May 11, 2019, 8:05pm UTC](https://discourse.julialang.org/t/how-are-functors-useful/24110/10 "2019-05-11T20:05:54Z")

</div>

I use it to add average execution time calculation and average frame rate calculation to arbitrary functions.

For functions that are part of a complex workflow whos running time is heavily dependent on the input(real-time image processing)

---

<div class="post-metadata">

**Author:** ![Raf](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/raf/32/3383_2.png) [@Raf](https://discourse.julialang.org/u/Raf)\
**Post date:** [May 12, 2019, 5:18am UTC](https://discourse.julialang.org/t/how-are-functors-useful/24110/11 "2019-05-12T05:18:44Z")

</div>

I’m providing a complex parametrisation method for users of my package. Defining the struct with default constructors is much clearer to users than telling them to use a closure with 8 arguments.

Then I can define show() methods, and use the same struct to build a user interface.

---

<div class="post-metadata">

**Author:** ![Vasily\_Pisarev](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/vasily_pisarev/32/7929_2.png) [@Vasily\_Pisarev](https://discourse.julialang.org/u/Vasily_Pisarev)\
**Post date:** [May 12, 2019, 5:32pm UTC](https://discourse.julialang.org/t/how-are-functors-useful/24110/12 "2019-05-12T17:32:01Z")

</div>

The functors can be understood in terms of multimethods and the generic `call()` function.  
We can say that the `f(x)` notation is a syntactic sugar for a special expression `call(f, x)`. We can say that the built-in `call()` is defined only for argument lists where the first element is bound to a lambda-expression, and defining a functor is just adding a method for the `call()` expression with the first argument of `struct` type.  
Much like adding a method to `getindex()` for a new type defines what `x[3]` means when `x` is of that type.

---

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [May 12, 2019, 9:12pm UTC](https://discourse.julialang.org/t/how-are-functors-useful/24110/13 "2019-05-12T21:12:56Z")

</div>

> [@Vasily\_Pisarev](#):
>
> The functors can be understood in terms of multimethods and the generic `call()` function.

Note that Julia [used to have a function](https://github.com/JuliaLang/julia/pull/8712) literally named `call` for this purpose, but it was [removed in Julia 0.5](https://github.com/JuliaLang/julia/pull/13412) in favor of the `(::T)(...) = ...` syntax.

---

<div class="post-metadata">

**Author:** ![tk3369](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tk3369/32/2824_2.png) [@tk3369](https://discourse.julialang.org/u/tk3369)\
**Post date:** [May 12, 2019, 9:20pm UTC](https://discourse.julialang.org/t/how-are-functors-useful/24110/14 "2019-05-12T21:20:32Z")

</div>

That sounds interesting. Do you mind sharing the code or is it already in some public repo?

---

<div class="post-metadata">

**Author:** ![Vasily\_Pisarev](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/vasily_pisarev/32/7929_2.png) [@Vasily\_Pisarev](https://discourse.julialang.org/u/Vasily_Pisarev)\
**Post date:** [May 12, 2019, 11:34pm UTC](https://discourse.julialang.org/t/how-are-functors-useful/24110/15 "2019-05-12T23:34:31Z")

</div>

TIL.  
I didn’t even know of Julialang at that time.  
So, one can change elements of mutable variables captured within closures. That’s crazy.

---

<div class="post-metadata">

**Author:** ![c42f](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/c42f/32/52842_2.png) [@c42f](https://discourse.julialang.org/u/c42f)\
**Post date:** [May 12, 2019, 11:56pm UTC](https://discourse.julialang.org/t/how-are-functors-useful/24110/16 "2019-05-12T23:56:41Z")

</div>

> [@Vasily\_Pisarev](#):
>
> So, one can change elements of mutable variables captured within closures

It’s not so unusual to be able to modify a mutable value captured by a closure. Even C++ lets you do that.

The behavior I still find truly surprising is that julia allows rebinding of new values to variable names which “belong” to an outer scope:

```julia
julia> function foo()
           i = 10
           some_closure = ()->(i = "Surprise")
           some_closure() # call the closure
           return i
       end
foo (generic function with 1 method)

julia> foo()
"Surprise"

```

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [May 13, 2019, 5:20am UTC](https://discourse.julialang.org/t/how-are-functors-useful/24110/17 "2019-05-13T05:20:12Z")

</div>

> [@Vasily\_Pisarev](#):
>
> So, one can change elements of mutable variables captured within closures. That’s crazy.

Not really, it’s just how closures work since Scheme (I guess, maybe earlier).

---

<div class="post-metadata">

**Author:** ![foobar\_lv2](https://avatars.discourse-cdn.com/v4/letter/f/ee59a6/32.png) [@foobar\_lv2](https://discourse.julialang.org/u/foobar_lv2)\
**Post date:** [May 13, 2019, 7:06am UTC](https://discourse.julialang.org/t/how-are-functors-useful/24110/18 "2019-05-13T07:06:53Z")

</div>

Function-like structs are just explicit closures. They have the advantage that you have full control over the layout, types, etc and also can add more methods / functionality, at the cost of some verbosity.

I mean this in a very literal sense: A very early step (lowering) transforms inner function definitions into definitions for callable structures, long before the optimizer does its work. Closures are mere syntactic sugar over callable structs, and I recommend to use explicit callable structs instead of implicit closures whenever the captured state is nontrivial.

---

<div class="post-metadata">

**Author:** ![tamasgal](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamasgal/32/27946_2.png) [@tamasgal](https://discourse.julialang.org/u/tamasgal)\
**Post date:** [May 13, 2019, 7:37am UTC](https://discourse.julialang.org/t/how-are-functors-useful/24110/19 "2019-05-13T07:37:26Z")

</div>

You guys made me rewrite a whole bunch of code where I had tons of `make_foo_function()` factory-style stuff to pass to optimisers etc.  
Thanks 😉

…and thanks again!

---

<div class="post-metadata">

**Author:** ![Vasily\_Pisarev](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/vasily_pisarev/32/7929_2.png) [@Vasily\_Pisarev](https://discourse.julialang.org/u/Vasily_Pisarev)\
**Post date:** [May 13, 2019, 6:55pm UTC](https://discourse.julialang.org/t/how-are-functors-useful/24110/20 "2019-05-13T18:55:37Z")

</div>

Oh, I mean,

```julia
function foo(x)
    z -> x*z
end

julia> f = foo([1, 2, 3])
#5 (generic function with 1 method)

julia> f(1)
3-element Array{Int64,1}:
 1
 2
 3

julia> f.x[1] = 42
42

julia> f(1)
3-element Array{Int64,1}:
 42
  2
  3

```

I thought, a name captured inside a closure is not supposed to be accessible by name from the scope the closure is exported into.

[Next page](https://discourse.julialang.org/t/how-are-functors-useful/24110.md?page=2)
