MRocklin
MRocklin

Reputation: 57271

Assert type information onto computed results in Julia

Problem

I read in an array of strings from a file.

julia> file = open("word-pairs.txt");
julia> lines = readlines(file);

But Julia doesn't know that they're strings.

julia> typeof(lines)
Array{Any,1}

Question

Can I tell Julia this somehow?

Is it possible to insert type information onto a computed result?

Upvotes: 2

Views: 310

Answers (3)

As of 0.3.4:

julia> typeof(lines)
Array{Union(ASCIIString,UTF8String),1}

I just wanted to warn against:

convert(Array{ASCIIString,1}, lines)

that can fail (for non-ASCII) while I guess, in this case nothing needs to be done, this should work:

convert(Array{UTF8String,1}, lines)

Upvotes: 0

tholy
tholy

Reputation: 12179

Isaiah is right about the limits of readlines. More generally, often you can say

n = length(A)::Int

when generic type inference fails but you can guarantee the type in your particular case.

Upvotes: 0

Isaiah Norton
Isaiah Norton

Reputation: 4366

It would be helpful to know the context where this is an issue, because there might be a better way to express what you need - or there could be a subtle bug somewhere.

Can I tell Julia this somehow?

No, because the readlines function explicitly creates an Any array (a = {}): https://github.com/JuliaLang/julia/blob/master/base/io.jl#L230

Is it possible to insert type information onto a computed result?

You can convert the array:

r = convert(Array{ASCIIString,1}, w)

Or, create your own readstrings function based on the link above, but using ASCIIString[] for the collection array instead of {}.

Upvotes: 1

Related Questions