guile-user
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Question about data structures


From: kwright
Subject: Re: Question about data structures
Date: Sun, 22 Nov 2020 15:58:08 -0500

divoplade <d@divoplade.fr> writes:

> Hello Zelphir!
>
> Le dimanche 22 novembre 2020 à 19:48 +0100, Zelphir Kaltstahl a écrit :
>> However, when I use the list in  reverse and ever need
>> to output the lines in the list in their original
>> order, I would first need to `reverse` the list again.
> There is a "reverse" function; you could implement it yourself as a
> tail-recursive function if you wanted (it's currently implemented in C,
> so my guess is it's even more efficient). You don't need vectors for
> that.
>
> (define (my-reverse-aux accumulation list)
>   (if (null? list)
>       accumulation
>       (my-reverse-aux (cons (car list) accumulation) (cdr list))))
>
> (define (my-reverse list)
>   (my-reverse-aux '() list))
>
> (my-reverse '(a b c d e f g h))

There is also a reverse! procedure.
  (reverse! '(a b c)) 
  $1 = (c b a)

I have not actually looked at the code, but I assume from the "!"
in the name and a decent respect for competence of the programmers,
that it uses the well-known algorithm to reverse a list by destructive
update.

This algorithm is still O(n), but who cares?  It is at least O(n)
to read n lines, no matter how how you read them.  The cost is
amortised and is only O(1) per line.  The thing to avoid is "cons".
The my-reverse procedure above still does O(n) times cons, which uses
storage, and may call garbage collection.

The destructive update algorithm does O(n) times update one storage
location and a couple of registers, which is trivial compared to
reading a line.

Just remember not to save pointers into the original non-reversed list,
because it gets smashed.  (You can still save pointers to the _members_
of the list.)

     -- Keith,

Programmer in Chief, Free Computer Shop,
http://www.free-comp-shop.com/
Food, Shelter, Source code

   



reply via email to

[Prev in Thread] Current Thread [Next in Thread]