Creating very similar types in Julia

Say I have two types that are subtypes of an abstract type

abstract A type B <: A x y z end type C <: A x y z w end 

Is there a way to create C without having to basically copy / paste B and add additional parameters? The main problem is that B and C really close, and I would prefer as little code duplication as possible. I know that the manual says that specific types cannot subtype each other:

One particularly distinctive feature of a Julias type system is that specific types cannot subtype each other: all specific types are final and can only have abstract types as their supertypes.

Is there any way around this?

+5
source share
3 answers

In these cases, I usually prefer to compose my types.

Here is an example of what I mean:

 abstract A type B <: A x y z end type C <: A b::B w end 

Note that C is still a subtype of A , but contains an instance of B as a field.

Update

It is true that you can no longer access cx , but you need to make cbx . There is an easy way to do this.

Suppose you have a function

 function my_func(a::A) # do something with ax, ay, az end 

If my_func should work with any subtype of A , it can only access fields that are common to all subtypes of A In this case, these are x , y and z .

Knowing this, I would also define a specialized version of this method for sending C instances as follows:

 my_func(c::C) = my_func(cb) 

This is a bit more verbose, but you can easily wrap all of these functions in metaprogramming for a loop that @eval uses and generates them all at once. See docs for more details.

+9
source

I would do

 type XYZ x y z end type B <: A xyz::XYZ end type C <: A xyz::XYZ w end 

Of course, for performance reasons, I usually use immutable , and also annotate as many types as possible.

+2
source

I do this with macros (as mentioned in the comments above). Subtypes remain divided, which is often more natural than sub-subtyping:

 abstract A macro A_fields() quote a1 a2 end end type B <: A @A_fields b1 end type C <: A @A_fields c1 end 

The main disadvantage is that when you cange A_fields() , you need to manually change all the constructors for subtypes of A

+1
source

All Articles