(d::Int)(x::Int) = d + x?

julia> (d::Int)(x::Int) = d + x # what does this mean ?

It defines a method so that you can call a Int (i.e. (d::Int)) with a single argument of type Int (i.e. x::Int) that returns the sum of the two.

Don’t define this method.


Also my first thought. What is that? That’s problematic and should be deleted.


It was in REPL syntax so I hope it either come from doing something random that didn’t error, or from a tutorial demostrating some funny/dangerous things that had a poor explaination.


Ppl please correct me if I am wrong, but I think this is called a “functor” but it’s not the same functor as in category theory.

It allows you to use an element of a type as a callable i.e. like a function.

You can do this for any type. But it doesn’t really make that much sense for integers. But there is precedent in Ruby where 3.times(fn) runs fn 3 times. But in Ruby everything is an object and their implementation causes performance issues IIUC.

(d::Int)(x::Int) = d + x

Basically, it says, any element d that is of Int type, you can now write d(x) and return d+x if x is also an Int.

E.g. y = 3; y(4) # yields 7

This kind of things is used in Flux.jl to make Dense layers easier to write. It’s almost like a function factory kinda thing.

See my tweet also https://twitter.com/search?q=julia%20ruby&src=typed_query

1 Like

Formally speaking this is just a method of Int which than makes Int a functor. It is not functor itself. As mentioned before this is a really bad idea for Int, but implementing method () provide useful syntax for function-like types, e.g. for own implementation of polynomials or different class of parametrisable operations.

1 Like