guile-user
[Top][All Lists]
Advanced

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

Re: References/locations


From: Kjetil S. Matheussen
Subject: Re: References/locations
Date: Fri, 08 Aug 2008 20:34:27 +0200 (CEST)



"Maciek Godek":
Subject: References/locations
To: address@hidden
Message-ID:
        <address@hidden>
Content-Type: text/plain; charset=ISO-8859-1

Hi,
it's me again, asking silly questions.

Not at all, your questions are very good. :-)



This time I would like to know if there's
a simple way to store a reference to
a variable in another variable -- say,
an element of vector or hash table.

I imagine this could look like this:
(define v #(1 2 3))
(define v1 (vector-location v 1))
v1
: 2
(set! v1 10)
v
: #(1 10 3)

I've tried to do it using a "procedure with
setter", but the problem is that set! doesn't
evaluate its first argument (as long as it's a
symbol), so I'd have to wrap everything
up in macros to obtain:
(set! (vector-location v 1) 10)

Besides I think that the names "hash-ref"
and "vector-ref" are confusing, since they
don't return references, but values (therefore
the names like "vector-get" or "hash-get" would
be more apropreate)


Never thought about that, but it sounds
correct. vector-get and hash-get would
probably be mroe apropreate names.



I also wonder if there's any point for allowing
locations to any sorts of variables (similar to
pointers in C or pointers to C++), that is,
(define x 10)
(define y (location x))
(set! y 20)
x
: 20


Well, here's a relatively clean way, I think:


(define-macro (location name)
   (define new-val (gensym))
   `(lambda (,new-val)
       (set! ,name ,new-val)))

(define old-set! set!)

(define-macro (set! a b)
  `(if (procedure? ,a)  ;; Needs a better check.
       (,a ,b)
       (old-set! ,a ,b)))


guile> (define x 10)
guile> (define y (location x))
guile> (set! y 20)
guile> x
20
guile>





reply via email to

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