A cool thing is that since the trait is now known at compile-time, some extra optimizations may happen, eg branches that depend on is_convex will be optimized away entirely:
Yea, here convexity would be defined per-function rather than per-method (which is how I took the original question, since Python doesn’t have methods).
@marius311 Thanks for your kind explanation, but in my example code, is_convex_repr does not act to determine whether a function is convex or not. Instead, it is more close to add a method like
Sorry should have called it just is_convex to more closely match your original question, I edited my post to reflect that. The only difference is that its a function is_convex(my_obj_path) instead of a property, my_obj_path.is_convex. If this isn’t what you’re asking for then I may be missing something.
This would be kinda weird to do in Julia but is kinda what u are looking for
struct IsConvexRepr{T}
fn
arg_types::T
is_convex::Bool
end
function (icr::IsConvexRepr)(args...)
@assert all(typeof.(args) .== icr.arg_types)
icr.fn(args...)
end
using MacroTools
macro is_convex_repr(b, ex)
@capture(ex, fn_(args__))
:(
IsConvexRepr($fn, typeof.($args), $b)
)
end
abc(x,y) = x+y
# you can define if it's convex by supplying an example of what to
# after all a method in julia is completely determined by function name and argument types
abc1 = @is_convex_repr false abc(1, 1)
abc2 = @is_convex_repr true abc(1.0, 1.0)
abc1(1, 1)
abc1(1.0, 1.0) # will error cos types don't match
abc2(1.0, 1.0)
abc2(1, 1) # will error cos types don't match
is_convex(x) = x.is_convex
is_convex(abc1) # false
abc1.is_convex # false
is_convex(abc2) # true
abc2.is_convex # true