Julian way to check for valid combination of inputs when defining function

What is the recommended way to do the following?

struct Relation
n::Int64
R::Set
end
Base.union(r1::Relation,r2::Relation) = if (some condition of r1 and r2) then …

I think when (some condition of r1 and r2) is rather complicated, then I have to explicitly do like the above. However, if I just want to check that r1.n==r2.n, can I do it somewhere on the left hand side?

Also which part of the documentation should I read to get more tips and tricks when working with defining/extending functions like above?

You may want a parametric type:

struct Relation{n}
  R :: Set
end

Base.union(r1 :: Relation{n}, r2 :: Relation{n}) where n = [...]
Base.union(r1 :: Relation{n1}, r2 :: Relation{n2}) where {n1, n2} = [...]

But this may take your example too literally.

For more complicated cases, Traits may work (e.g., GitHub - mauro3/SimpleTraits.jl: Simple Traits for Julia). But it depends on exactly what the comparison is.

As for extending Base functions, there are various threads here on discourse, such as

2 Likes