guile-user
[Top][All Lists]
Advanced

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

Re: assign to and read from global variable


From: tomas
Subject: Re: assign to and read from global variable
Date: Fri, 20 Mar 2020 18:33:32 +0100
User-agent: Mutt/1.5.21 (2010-09-15)

On Fri, Mar 20, 2020 at 06:20:38PM +0100, Malte Frank Gerdes wrote:
> Hi,
> 
> i'm trying to collect every definition of variables with it's according
> value in a global variable. How i think it's supposed to work is:
> 
> (define *global* '())
> 
> (...
>   (defvar . ,(lambda (_ . args)
>                (set! *global* (cons *global* args))))
>  ...)
> 
> 
> 
> This results in the following output:
> ((()
    ^^ Here's your initial "global"

I.e.:

  scheme@(guile-user)> (cons '() 'a)
  $1 = (() . a)

(in box-and-pointer notation: you start with an empty list,
then you append 'a, you end up with:

   | | | -> | | | -> nil
    |        |
    v        v
   nil       a

(sorry for my poor drawing skills).

If you keep consing at the end of your thing, the nesting
gets deeper and deeper:

  scheme@(guile-user)> (define g '())
  scheme@(guile-user)> (set! g (cons g 'a))
  scheme@(guile-user)> (set! g (cons g 'b))
  scheme@(guile-user)> (set! g (cons g 'c))
  scheme@(guile-user)> g
  $2 = (((() . a) . b) . c)

I guess that's not what you want.

One "classical" idiom to achieve what you're looking for
is to prepend your new stuff onto the list, and at the
end revert it:

  scheme@(guile-user)> (define g '())
  scheme@(guile-user)> (set! g (cons 'a g))
  scheme@(guile-user)> (set! g (cons 'b g))
  scheme@(guile-user)> (set! g (cons 'c g))
  scheme@(guile-user)> g
  $3 = (c b a)

Ah. That looks better. But... it's tail first!

  scheme@(guile-user)> (reverse g)
  $4 = (a b c)

That's it.

Of course there are other ways to achieve this, like
keeping a pointer to the list's tail, using vectors
and so on. But in lispy world, and for smallish
things, the above is, as far as I konw, the usual
idiom.

Cheers
-- t

Attachment: signature.asc
Description: Digital signature


reply via email to

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