Constructing a function at runtime to pass as an argument

HI,

I’m trying to create a function at runtime to pass as a parameter to another function (Agents.random_agent to be exact). I can pass a condition but the condition is dependant on the state of the current agent so I need to somehow add that.

In case this all sounds confusing, here’s what I’m trying to do:

The random_agent function is defined as follows:

random_agent(model, condition)

I have defined the agents as follows (simplified version of actual code):

struct MyAgent # <: AbstractAgent - this is only useful when working with the actual agents but doesn't really matter here.
    id::Int
    state::Int
    triggers_on_state::Int
end

function foo(model, agent::MyAgent)
    # construct a function f(agent) that returns true when an agent's triggers_on_state equal the state of the agent passed to foo.
    an_agent = random_agent(model, f)
end

How do I construct f in such a way I can construct a different f on each call of foo()?

Thanks in advance,
Stef

Could f receive two parameters and be passed like a closure?

f(agent,state) = ....
an_agent = random_agent(model, state -> f(agent, state))

Then inside random_agent you can check the condition, without having to define the function at runtime.

The problem is that random_agent is not my code, it’s part of a package.

Uhm, that is not necessarily an impediment to the approach above.

2 Likes

Ah, I see. I haven’t worked with closures yet and made a wrong assumption. Is there some more in depth documentation on closures somewhere? The chapter in the reference manual is a bit too dense for me.

Thanks!

I have some personal notes here, maybe they are helpful: https://m3g.github.io/JuliaNotes.jl/stable/closures/

1 Like

Thanks!

1 Like