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

Re: environments for lambda-closures



> is there any way to access and set the lexical environments for 
> compiled lambda closures?  

Yes: write some C code.  See below.

> basically, i want to change the
> lexical environment for a compiled lambda closure dynamically.
> the reason for wanting to do this is so that i can share the
> "body" of the closure across different lexical environments.

This sounds more like you want to set the code address rather
than the environment.  That is, it seems that you want several
different closures with different environments but the same code
(so you need to set the code to be the same) and not several
different closures with different code but the same environment
(where you have to set the environments to be the same).

If this is so, you may not need to set anything at all.  The
procedure MC in the example below returns closures with different
environments but the same code.  You may be able to arrange things
to have something like that work for you.

Anyway, the code below should work and has been tested on a 4.2 VAX.

----------------------------------------------------------------------

(defCfun "object get_cc_env(cc) object cc;" 0
  "return ((type_of(cc) == t_cclosure) ? cc->cc_env : Cnil);")

(defentry get-cc-env (object) (object get_cc_env))

(defCfun "object set_cc_env(cc,e) object cc,e;" 0
  "return ((type_of(cc) == t_cclosure) ? cc->cc_env = e : Cnil);")

(defentry set-cc-env (object object) (object set_cc_env))

(defsetf get-cc-env set-cc-env)

----------------------------------------------------------------------

>(defun mc (n) #'(lambda () (incf n)))
MC

>(compile 'mc)
End of Pass 1.
End of Pass 2.

>(setq c1 (mc 10))
#<compiled-closure 00151d58>

>(get-cc-env c1)
(10)

>(funcall c1)
11

>(get-cc-env c1)
(11)

>(setf (get-cc-env c1) (list 100))
(100)

>(get-cc-env c1)
(100)

>(funcall c1)
101

>(funcall c1)
102

>(get-cc-env c1)
(102)

----------------------------------------------------------------------

Jeff Dalton,                      JANET: J.Dalton@uk.ac.ed             
AI Applications Institute,        ARPA:  J.Dalton%uk.ac.ed@nss.cs.ucl.ac.uk
Edinburgh University.             UUCP:  ...!ukc!ed.ac.uk!J.Dalton