Type-Instability Caused by Wrapping Type-Stable Function

This line shows that, within f, it is unknown what prior_struct.eval_logprior is. This is (almost certainly, although your example was incomplete so some chance I’m wrong) because prior_struct is a non-constant global variable.

If you wrote this same code inside a function (or some other place where prior_struct was of known type), it would probably be fine.

What might work in your above example (in the REPL) is to instead define f as

f = let eval_logprior=prior_struct.eval_logprior
    (x)->eval_logprior(x)
end

which is essentially what worked for you the first time. Although getting this into a local scope is the better solution. I didn’t get to verify this so I might have made a minor mistake.

BEGIN EDIT:

The other issue that might might be in play is that you might have written

struct Prior_Struct_Type
    # stuff
    eval_logprior::Function
    # stuff
end

Function is /not/ a concrete type (it is an abstract type) so this field is non-concretely typed and any access will be type-unstable. Instead, you can use a parametric type

struct Prior_Struct_Type{F}
# or Prior_Struct_Type{F<:Function} to require that eval_logprior is a Function, but this has no performance benefit
    # stuff
    eval_logprior::F
    # stuff
end

which will be stable.

5 Likes