AbstractStrings, Strings, and their Arrays

Hi,

I know from reading the Julia documentation (and experimenting), that although String <: AbstractString is true, Array{String} <: Array{AbstractString} is false. So if I have a function that needs to accept an array of all types of strings, what is the right way?

Option 1:

function myFunction(instr::Array{AbstractString,1})
:
end

function myFunction(instr::Array{String,1})
:
end

Option 2:

function myFunction(instr::Union{Array{AbstractString,1}, Array{String,1}})
:
end

Is there a preferred way to do this? Are there performance penalties in using either of these options?

Thanks,
Ravi

Why not using Parametric Methods

function myFunction{T <: AbstractString}(instr::Array{T,1})
:
end
function myFunction{S <: String}(instr::Array{S})
...
end

or on 0.6

function myFunction(instr::Array{S}) where S <: String
...
end

http://docs.julialang.org/en/release-0.5/manual/methods/#parametric-methods

(oh and it should really be AbstractArray because function arguments should dispatch on abstract types, but I didn’t change that to not cause additional confusion).

EDIT: Overlapping responses with the above :slight_smile:

Two cents from me, you can write it like this on Julia 0.6:

julia> Vector{<:AbstractString}
Array{#s1,1} where #s1<:AbstractString

2 Likes

awesome

Thank you all!

Is there a reason you use String and not AbstractString here? So in effect, shouldn’t it be:

function myFunction{S <: AbstractString}(instr::AbstractArray{S})
...
end
1 Like

For some reason I’d gotten into my head that String was the new abstract type for strings, but it isn’t. So String was just wrong :slight_smile: