Basically I want a dynamic union of singleton types.
Traits.
f(x::T) where T = _f(Val(Base.issingletontype(T)), x)
_f(::Val{true}, x) = "I am a singleton"
_f(::Val{false}, x) = "I ain't a singleton, I have a gazillion of possible values."
julia> f(Base.HasLength())
"I am a singleton"
julia> f([1])
"I ain't a singleton, I have a gazillion of possible values."
2 Likes
There’s nothing built into the language (other than custom trait solutions) that allows you to dispatch on arbitrary predicates, no.
2 Likes
Thanks. However I don’t own the function name so I can’t change the general fallback.
You can wrap the function then in a similar way, eg
f(x::T) where T = _f(Val(Base.issingletontype(T)), x)
_f(::Val{true}, x) = "I am a singleton"
_f(::Val{false}, x) = g(x) # g is the function you do not own
and use f
for your own purposes.
If this is not possible, you can make a feature request for the package that owns g
, to add a trait-based extension.
3 Likes