Mike75
Mike75

Reputation: 524

Julia function without name and with double parenthesis

This is a "beginning with Julia"-question.

I read some basic Julia function tutorials, but could not yet find the sense of double parenthesis, like in this example (from JuliaReinforcement RandomWalk1D):

function (env::RandomWalk1D)(action)
    env.pos = max(min(env.pos + env.actions[action], env.N), 1)
end

What does the double parenthesis (without function name??) mean here? When and how is this function called?

Thank you!

Upvotes: 3

Views: 297

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69869

I assume you refer to the source of the package that can be found here.

This kind of definition creates a functor. See here in the documentation for an explanation.

The idea is simple. You want to be able to call a value just like you would call a function. Here is a minimal example:

julia> struct A
           v
       end

julia> (x::A)() = x.v

julia> a = A(100)
A(100)

julia> a()
100

Note that in this example a is a value, but still you can call it with a() as if it were a function.

If something is not clear please comment and I can expand on it.

Upvotes: 4

Related Questions