Parametrizing a self-referential function field

My struct changes its input function to automatically get the struct as an argument. This works if I don’t type the struct, but I have no idea how I can type it.

mutable struct CoronaModel{F1}
    # other fields omitted
    nextSickness::F1
    function CoronaModel{F1}(nextSickness) where {F1}
        me = new()
        me.nextSickness = (p) -> nextSickness(me, p)
        me
    end
end

I’m not sure what you’re trying to do here, so I may be way off.

But you seem to want your function to have access to the internal fields of your struct?
Then maybe consider calling the struct as a function?

mutable struct CoronaModel
    a::Int
    b::Int
end

function (model::CoronaModel)(p)
    return model.a + model.b + p
end

Then you can “call” an object m::CoronaModel with argument p

julia> m = CoronaModel(2,5)
CoronaModel(2, 5)

julia> m(8)
15

julia> m.a = 3
3

julia> m(8)
16
2 Likes

That wouldn’t work, because I want the function “nextSickness” to be itself customizable by the creator of the struct. Different CoronaModel instances will have different “nextSickness” functions. This function will be given with the signature (::CoronaModel,::SthElse) to the constructor of CoronaModel, and the constructor will wrap it around so that it can be called by merely supplying (::SthElse).
To rephrase; I want the struct to accept a function field that has access to the struct’s fields.

I am still not sure what you are trying to do here, but note that there is no Julia equivalent of self etc in various OOP languages, so you may just need to use a different approach.

Well, I just dropped parametrizing on that function field for a perf penalty. Otherwise, I can simulate the self behavior perfectly. I am content. :slight_smile: