Prepend! usage / what methods to implement?



What methods should i be implementing if i am to use prepend! on a user defined datatype? Can you show me an example?

julia> struct R
julia> function f(r::R)
           linearized = R[]
f (generic function with 1 method)

julia> f(R(3))
ERROR: MethodError: no method matching length(::R)
Closest candidates are:
  length(::SimpleVector) at essentials.jl:256
  length(::Base.MethodList) at reflection.jl:558
  length(::MethodTable) at reflection.jl:634
 [1] _prepend!(::Array{R,1}, ::Base.HasLength, ::R) at ./array.jl:722
 [2] f(::R) at ./REPL[7]:3


A custom type with no parent type basically doesn’t know how to do anything. Try implementing the length method and then see what fails after you implement that. When the code stops failing, you’ve implemented enough methods. What data structure are you trying to implement?


I have a hunch that you actually want to be calling unshift!(linearized,r) (it has a better name on 0.7: pushfirst!).

prepend! and append! tack two collections together. push! and unshift! add a single element to a collection.


Ah yes, that does seem likely. I (probably) took the question too literally.