Prepend! usage / what methods to implement?


#1

Hi,

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

julia> struct R
           x::Int
       end
julia> function f(r::R)
           linearized = R[]
           prepend!(linearized,r)
           linearized
       end
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
  ...
Stacktrace:
 [1] _prepend!(::Array{R,1}, ::Base.HasLength, ::R) at ./array.jl:722
 [2] f(::R) at ./REPL[7]:3

#2

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?


#3

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.


#4

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