You could easily improve the latter one by helping the compiler with type 
inference, though:

julia> a
3-element Array{Number,1}:
 1
 2
 3

julia> reshape([ a[i]::Number for i=1:length(a) ], size(a))
3-element Array{Number,1}:
 1
 2
 3

The reason this doesn't work well in the global scope is that type 
inference in general doesn't. The only thing I added was ::Number inside 
the comprehension, which lets the compiler know that this will turn out as 
an array of numbers. In fact, we could make this even tighter if we knew 
what kind of numbers they were:

julia> reshape([ a[i]::Int64 for i=1:length(a) ], size(a))
3-element Array{Int64,1}:
 1
 2
 3

a is still just declared as Array{Number,1}, but since all the elements of 
a are ints, it works. If we were to add a non-Int64 number to a and try 
again, we'd get a type error during execution. (But if we wanted to 
accomplish the same thing inside foo, we'd probably do it with a type 
parametrization, and get a method error instead, so both cases are really 
just as good).

I guess the lesson here is that if you're going to do stuff in the global 
scope and want tight type inference, you'll have to give the compiler some 
help. Given the first section in the performance 
tips<http://docs.julialang.org/en/latest/manual/performance-tips/> chapter 
in the manual, this shouldn't come as a surprise =)

// Tomas



On Wednesday, April 30, 2014 3:04:02 PM UTC+2, Patrick O'Leary wrote:
>
> While not as tight as it could be, neither is the original typeassert. 
> Array{Number} is still going to store pointers to the values, since Number 
> is an abstract type, so if the question is about storage and access 
> efficiency, inference as Array{Any} doesn't actually change anything.
>
> On Wednesday, April 30, 2014 6:41:55 AM UTC-5, Ariel Keselman wrote:
>>
>> see simplified behavior below:
>>
>>
>> <https://lh4.googleusercontent.com/-buanLj1oJlU/U2DhZ4Fo2XI/AAAAAAAAHS4/xC8WkdiahEM/s1600/Capture1.PNG>
>>
>>
>>

Reply via email to