Pregunta

I'm entirely new to Julia (just started earlier today), so forgive me if this is a silly question, but despite loving the language, I'm not finding a lot of great debugging help out there.

Basically I just want to define an alternate constructor for a method that will activate on input of an Array containing any type of Integer (int32, uint8, etc...).

I thought this would be relatively simple and wrote the following:

type MyType
    weight_matrices::Array{Array{FloatingPoint}}

    MyType(layer_sizes::Array{Integer}) =
        new([
            rand(layer_sizes[i], layer_sizes[i+1]) for i in [1:length(layer_sizes)-1]
        ])
end

but when I tried using it:

test = MyType([1,2,1])

I get the error:

ERROR: no method MyType(Array{Int64, 1})

Switching the alternate constructor from Array{Integer} to Array{Int64} solves the problem as one would assume, but I don't want to restrict the usage that far.

Any idea on how to do this? Any code review would also be much appreciated. I assume this code isn't very "Julian" (is that a thing?) and would love pointers to make this more usable by others.

¿Fue útil?

Solución

This works:

type MyType     
       weight_matrices::Array{Array{FloatingPoint}}

       MyType(layer_sizes::Array{Int}) =
           new([
               rand(layer_sizes[i], layer_sizes[i+1]) for i in [1:length(layer_sizes)-1]
           ])
   end

julia> test = MyType([1,2,1])
MyType([
1x2 Array{FloatingPoint,2}:
 0.477698  0.454376,

2x1 Array{FloatingPoint,2}:
 0.318465
 0.280079])

Julia containers are not co- or contra-variant, so [1,2,1], which is an array of concrete type Int is not a subtype of an array of abstract type Integer

(Note, Int is an alias for your native integer type, Int64 on 64 bit machines, Int32 on 32 bit machines)

If you really want your input to be different types of integers, then parameterise the type of the input (using an outer constructor)

type MyType                                
       weight_matrices::Array{Array{FloatingPoint}}
end

MyType{T<:Integer}(layer_sizes::Array{T}) =
           MyType([rand(layer_sizes[i], layer_sizes[i+1]) for i in                   [1:length(layer_sizes)-1]])

julia> test = MyType([1,2,1])
MyType([
 1x2 Array{FloatingPoint,2}:
 0.28085  0.10863,

2x1 Array{FloatingPoint,2}:
 0.245685
 0.277009])
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top