Abstract types and inheritance in Julia

Suppose I define a function on an abstract type A in Julia:

abstract A function mysum(a::A) ax + ay end 

Implicitly, any subtype must have x and y fields for this function to work. Thus, the functions defined on A define the requirements for subtypes. These functions could be written anywhere, and one could imagine a situation where functions are much more complex and requirements are more difficult to detect. Is it possible to somehow declare requirements, a subtype of an abstract type must have, in addition to simply implicitly from functions?

This is similar to Julia # 6975 , but if it is not related to this, someone can clarify the difference.

Finally, why does someone want to use type union instead of an abstract type. The abstract type is more flexible and extensible, the union of types is fixed. for instance

Why is this:

 type A x end type B x end typealias C Union{A,B} 

Instead of this:

 abstract C type A <: C x end type B <: C x end 
+6
source share
1 answer

First question: I don’t think there is a way to achieve this at the moment, but it underlies the discussions about adding traits to the language. You have already found one question discussing this, and I believe that it is on an unofficial roadmap that goes beyond version 1.0 (at least I already mentioned this).

I think the recommended way to implement what you are looking for is something like that:

 abstract A type B <: A x y end type C <: A w z end prop1(b::B) = bx prop2(b::B) = by prop1(c::C) = cw prop2(c::C) = cz # changed from prop2(c::C)=cw mysum(a::A) = prop1(a) + prop2(a) 

That is, instead of requiring that B and C have the same fields, you implement methods that determine their behavior. Then the actual field names remain the internal implementation details of each particular type.

As for union types, they can be used (among other things) to add methods to types that do not have a common supertype. Abstract types are beautiful, but you cannot always fit all of your types into a common hierarchy, and often you will add methods to sets of types that you yourself have not defined.

+6
source

Source: https://habr.com/ru/post/1011631/


All Articles