On Tuesday, January 12, 2016 at 1:04:26 PM UTC-5, Christian Winkler wrote:
>
> Suppose I have two types, and a Union of those two types. As expected, I 
> can pass either type in as an argument to a function where the 
> corresponding function argument is annotated with the Union:
>

See this thread

https://groups.google.com/forum/?fromgroups=#!topic/julia-users/daqcSANzgmo
 

>
> julia> type TypeA; a::Float64; end
>
> julia> type TypeB; a::Float64; b::Float64; end
>
> julia> TypeAorB = Union{TypeA,TypeB}
> Union{TypeA,TypeB}
>
> julia> function foo(x::TypeAorB); x.a + 3; end
> foo (generic function with 1 method)
>
> julia> a = TypeA(1.5)
> TypeA(1.5)
>
> julia> foo(a)
> 4.5
>
>
> I can define a function that takes an argument which is an array whose 
> elements are members of that Union:
>
> julia> function foovec(x::Vector{TypeAorB}); [foo(xi) for xi in x]; end
> foovec (generic function with 1 method)
>
> julia> methods(foovec)
> # 1 method for generic function "foovec":
> foovec(x::Array{Union{TypeA,TypeB},1}) at none:1
>
>
> However, if I try to pass in any vector whose elements are of TypeA or 
> TypeB, I get an unexpected (to me at least) failure:
>
> julia> foovec([a,a])
> ERROR: MethodError: `foovec` has no method matching 
> foovec(::Array{TypeA,1})
>
>
> In my real use case, the vectors never mix elements from my two types, so 
> I can get the behavior that I want using a second Union (of vector types):
>
> julia> TypeAorBvec = Union{Vector{TypeA},Vector{TypeB}}
> Union{Array{TypeA,1},Array{TypeB,1}}
>
> julia> function foovec(x::TypeAorBvec); [foo(xi) for xi in x]; end
> foovec (generic function with 2 methods)
>
> julia> foovec([a,a])
> 2-element Array{Float64,1}:
>  4.5
>  4.5
>
>
> But I would like to know why the first example does not work.
>
> An even simpler example: if I define a function with an argument of type 
> Vector{Any}, then I cannot pass in an array of TypeA, again I get a "no 
> method matching" error.
>
>
>
>
>
>
>
> Please click here 
> <http://www.e-disclaimer.com/conning/AD21D06B4CC99D2B4F24BA73FB4EED83.htm> 
> for 
> important information regarding this e-mail communication.
>

Reply via email to