Set disjunction for arguments, if defining a function

If you define a function, can you set disjunctions for the arguments? For example;

function simpleadd(a::Float64||Int64, b::Float64||Int64)
       a + b
end

I could use Any, but this alternative would be more expressive and definitive.

Are you looking for Union{Float64,Int64}? A good overview can be found here.

5 Likes

Thanks.

Not exactly looking for that, but really for what’s in the example.

It still works, of course, and so far comes closest to what I was looking for. It will do.

Can you explain what you’re actually looking for? Do you just want an infix operator to express Union, or are you actually looking for different semantics?

Pretty much like it’s in the example: you use the existing disjunction operator || to signify a disjunction for the argument type. The Union way proposed works and is equivalent results-wise.

It’s possible to do this with the | operator:

julia> Base.:|(::Type{T}, ::Type{S}) where {T,S} = Union{T,S}

julia> simpleadd(a::(Float64|Int64), b::(Float64|Int64)) = a + b
simpleadd (generic function with 1 method)

julia> simpleadd(3, 4.2)
7.2

julia> methods(simpleadd)
# 1 method for generic function "simpleadd":
[1] simpleadd(a::Union{Float64, Int64}, b::Union{Float64, Int64})

I wouldn’t recommend it though — defining an idiosyncratic syntax for Union will make your code harder for other Julia programmers to read, not to mention the fact that this is type piracy and hence not composable (if someone else overloads | for types).

1 Like

You could use a different infix operator than | so that it’s not type-piracy:

julia> ∨(::Type{T}, ::Type{S}) where {T, S} = Union{T,S}
∨ (generic function with 1 method)

julia> simpleadd(a::(Float64∨Int64), b::(Float64∨Int64)) = a + b
simpleadd (generic function with 1 method)

julia> simpleadd(3, 4.2)
7.2

julia> methods(simpleadd)
# 1 method for generic function "simpleadd":
[1] simpleadd(a::Union{Float64, Int64}, b::Union{Float64, Int64}) in Main at REPL[4]:1

It’s probably still a bad idea, but I have to admit I’ve done crap similar to this when I got tired of writing Union{whatever,Missing}.

1 Like

Hah hah hah! Beautiful! You people certainly surprise me. I still have to try it out, but it sure looks good.

But for some reason it gives me an error:
UndefVarError: Float64¥Int64 not defined

It looks like ¥ is parsed as part of an identifier (it’s as if you typed Float64XInt64, which is just a long name for a variable which does not exist). You can find a list of unicode symbols which are parsed as operators here: https://github.com/JuliaLang/julia/blob/b29d95119d1f1bd485ba015c2bbfc9b08fcc09b9/src/julia-parser.scm#L16-L38