JuliaLang / julia

The Julia Programming Language
https://julialang.org/
MIT License
45.7k stars 5.48k forks source link

AnnotatedString constructor too restrictive #55245

Closed aplavin closed 2 weeks ago

aplavin commented 3 months ago
julia> anns = [:x => "a", :y => 1]

# this works:
julia> Base.AnnotatedString("abc def", [(i:i, anns[i]) for i in 1:2])
"abc def"

# but after replacing 2 with 0 doesn't:
julia> Base.AnnotatedString("abc def", [(i:i, anns[i]) for i in 1:0])
ERROR: MethodError: no method matching Base.AnnotatedString(::String, ::Vector{Tuple{UnitRange{Int64}, Any}})

I think the constructor type constraints are too restrictive.

nsajko commented 3 months ago
julia> eltype([(i:i, anns[i]) for i in 1:0])
Tuple{UnitRange{Int64}, Any}

julia> eltype([(i:i, anns[i]) for i in 1:2])
Tuple{UnitRange{Int64}, Pair{Symbol, Any}}

You could specify the element type when constructing the vector, though.

KristofferC commented 3 months ago

Seems better to verify during construction than to restrict the container type, or?

tecosaur commented 3 months ago

We could define something like

AnnotatedString(str::AbstractString, itr) =
    AnnotatedString(str, Tuple{UnitRange{Int64}, Pair{Symbol, Any}}(collect(itr)))

Thoughts?

tecosaur commented 2 months ago

If that seem good, I'll happily whip up a PR.