in reply to No Iterators Allowed

Of course, cdr doesn't have to be O(N) if you implement lists like lisp does (in Lisp, lists are just particular arrangements of 2-element cons cells):
# pack 2 elements into a cons cell # if the second element is a cons cell or undef, the result is conside +red a list sub cons { [$_[0],$_[1]]; } # return the first element in a list. # or to put it another way, return the first of the 2 elements of the +given cell sub car { ref $_[0] ? $_[0][0] : undef; } # return the "remaining list" (everything except the first element) in + a list. # or to put it another way, return the second element of a cons cell sub cdr { ref $_[0] ? $_[0][1] : undef; }
The disadvantage ofcourse is that these lists don't act like perl arrays.

update: fixed the cdr() definition

Replies are listed 'Best First'.
Re^2: No Iterators Allowed
by runrig (Abbot) on Feb 27, 2008 at 23:47 UTC
    Yeah, I know I could have implemented real linked lists, but I just wanted to keep things simple, and also, it would make the initialization of the passed in lists messier looking :-)

    But it would be nice if you could make it O(1) anyway without linked lists.

      But it would be nice if you could make it O(1) anyway without linked lists.
      You could implement cdr as returning a shared hash slice. With some XS hacking you can probably make it work for some cases. Though you may have to make arrays immutable to do it right :-)

      update: it seems to me you could implement this in pure perl using tied arrays. But it would get more inefficient for each slice-of-a-slice-of-a-slice.