Possible bug in prepend!?

Came across the following unexpected asymmetric behaviour for push! and prepend!

B = Vector{Date}()
prepend!(B,Date(2021,2,2))      # Errors

A = Vector{Date}()      
push!(A,Date(2021,2,2))         # OK 

But

B = Vector{Date}()
prepend!(B,[Date(2021,2,2)])    # OK

A = Vector{Date}()
push!(A,[Date(2021,2,2)])       # Errors

Also,

A = Vector{Float64}()       
push!(A,1.0)                # OK

B = Vector{Float64}()       
prepend!(B,1.0)             # OK

A = Vector{Float64}()       
push!(A,[1.0])              # Errors

B = Vector{Float64}()
prepend!(B,[1.0])           # OK

Shouldn’t the behaviour of push! and prepend! be similar in terms of throwing errors?

Also, although the behaviour of push! is consistent across types, it seems that such is not the case for prepend! (B = Vector{Float64}(); prepend!(B,1.0) runs fine, but B = Vector{Date}(); prepend!(B,Date(2021,2,2)) errors, as shown above)

You are looking for pushfirst!. prepend!, like append!, expects multiple entries to iterate over and push into the collection.

Examples:

julia> A = Int[0]
1-element Vector{Int64}:
 0

julia> push!(A, 1)
2-element Vector{Int64}:
 0
 1

julia> pushfirst!(A, -1)
3-element Vector{Int64}:
 -1
  0
  1

julia> append!(A, [2, 3])
5-element Vector{Int64}:
 -1
  0
  1
  2
  3

julia> prepend!(A, [-3, -2])
7-element Vector{Int64}:
 -3
 -2
 -1
  0
  1
  2
  3
6 Likes

Thank you for the clarification. It makes sense. But still should B = Vector{Float64}(); prepend!(B,1.0) run fine, and B = Vector{Date}(); prepend!(B,Date(2021,2,2)) error?

That’s because numbers are iterable (they act as a collection with one element).

2 Likes

I see, interesting. Thank you