Why does this list comprehension return Array {Any, 1} instead of Array {Symbol, 1}?

When I try to create an Array with a list, this leads to Array{Any, 1} , even if I encode all the elements into a "character":

 julia> u_col_names=[symbol("user_id"), symbol("age"), symbol("sex"), symbol("occupation"), symbol("zip_code")] 5-element Array{Symbol,1}: :user_id :age :sex :occupation :zip_code julia> col_names=["user_id", "age", "sex", "occupation", "zip_code"] 5-element Array{ASCIIString,1}: "user_id" "age" "sex" "occupation" "zip_code" julia> u_col_names=[symbol(col_names[i]) for i in 1:size(col_names)[1]] 5-element Array{Any,1}: :user_id :age :sex :occupation :zip_code 

Why does the last list comprehension return Array{Any, 1} instead of Array{Symbol, 1} ? Note that the following returns Array{Symbol, 1} :

 julia> u_col_names=[symbol("col_names$i") for i in 1:size(col_names)[1]] 5-element Array{Symbol,1}: :col_names1 :col_names2 :col_names3 :col_names4 :col_names5 

Interestingly, the following does:

 julia> col_names[1] "user_id" julia> symbol(col_names[1]) :user_id julia> [symbol(col_names[1]), symbol(col_names[2])] 2-element Array{Symbol,1}: :user_id :age 

What am I missing?

+7
arrays type-inference julia-lang
source share
1 answer

According to this discussion in the JuliaLang/julia repo problem tracker on GitHub , the problem seems to be related to the lack of Julia's I / O system. Jeff Besancon (one of the authors and accompanying Julia) left a corresponding comment in another discussion :

This behavior is actually expected at the moment. Since [ col_names ] is global, it can change anywhere, so we cannot assume that we know its type. It's overly pessimistic, but it's hard to come up with a rule that would allow us to do better.

Surprisingly, but perhaps ( as John Myles White noted ), the type is correctly inferred if these operations are performed inside the function:

 julia> function fun() col_names=["user_id", "age", "sex", "occupation", "zip_code"] return u_col_names=[symbol(item) for item in col_names] end fun (generic function with 1 method) julia> fun() 5-element Array{Symbol,1}: :user_id :age :sex :occupation :zip_code 

As an alternative to list comprehension, you can use map(symbol, <Array{T,1}>) , which returns Array{Symbol,1} , even in the global scope:

 julia> col_names=["user_id", "age", "sex", "occupation", "zip_code"] 5-element Array{ASCIIString,1}: "user_id" "age" "sex" "occupation" "zip_code" julia> map(symbol, col_names) 5-element Array{Symbol,1}: :user_id :age :sex :occupation :zip_code 
+8
source share

All Articles