Type unstable & factory constructor

Say I have a type hierarchy

abstract A
immutable B <: A end
immutable C <: A end

The constructor Afollows the factory pattern:

function A(x::Int)
    if x > 0
        B()
    else
        C()
    end
end

It returns different subtypes based on input as expected. However, it is also type unstable, as I cannot find a way to make the return type be A.

So, is it bad to have a factory pattern here? Type instability affects only immutable types, not mutable types, since the latter is a reference type.

Do I need to choose a parametric type for this?

immutable D{T <: A}
    type::T
end

function D(x::Int)
    if x > 0
        D(B())
    else
        D(C())
    end
end

He's feeling a little bad.

Actually, how bad is it to have a type of unstable functions? Should I trade for better readability of the code?

Alternatively, should one typealias A Union{B,C}define instead ?

+4
1

, :

function A(x::Int)
    if x > 0
        B()::A
    else
        C()::A
    end
end

:

julia> @code_warntype A(5)
Variables:
  x::Int64

Body:
  begin  # none, line 2:
      unless (Base.slt_int)(0,x::Int64)::Bool goto 0 # none, line 3:
      return $(Expr(:new, :((top(getfield))(Main,:B)::Type{B})))
      goto 1
      0:  # none, line 5:
      return $(Expr(:new, :((top(getfield))(Main,:C)::Type{C})))
      1: 
  end::Union{B,C}

. , julia " ", , . , , " A", , - ( ).

factory, , . :

A(x::Vector) = B()
A(x::Matrix) = C()

A.

, Val:

A(x, ::Type{Val{1}}) = B()
A(x, ::Type{Val{2}}) = C()

A(1, Val{1})   # returns B()
A(1, Val{2})   # returns C()
+5

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


All Articles