The docstring for empty states that
empty(v::AbstractVector, [eltype])
Create an empty vector similar to v, optionally changing the eltype.
The method, though, is defined as
empty(a::AbstractVector{T}, ::Type{U}=T) where {T,U} = Vector{U}()
This works, but I wonder why it doesn’t call similar(a, U, 0)
instead? Wouldn’t this be more in line with the docstring? And it should fall back to a Vector
anyway, if no specializations are available.
3 Likes
JuliaLang:master
← JuliaLang:ajf/empty
opened 06:57AM - 29 Oct 17 UTC
This work relates to #24019, the theme of which is making the indexing interface… for `AbstractArray` and `Associative` much more similar (which I hope will make working with containers more seamless).
For arrays, `similar` returns arrays with the same `keys`, whereas for dictionaries, `similar` returns empty dictionaries. If we are going to make the semantics of indexing and so-on more consistent between arrays and dicts, then to me it makes sense to have:
* An `empty` function which is the functional companion of mutating `empty!` and predicate `isempty`, and replaces `similar(::Associative)`.
* A `similar` function that always preserves the existence of indices. *Occasionally* this might be a nice performance hack for creating new `Dict`s, but much more importantly this will be very useful for user-defined `Associative`s which may have immutable or expensive-to-insert keys, but freely mutable values.
I'm a bit new to the `Associative` code base... Please note that the signatures I've created for `empty` and `similar` make more sense in a world where `Associatives` iterate values, not key-value `Pair`s, which is another breaking (v1.0) suggestion in #24019.
I’m not sure; seems like a good idea to use similar
here.