Search code examples
schemeenvironmentguile

How to inspect/export/serialize a (guile) Scheme environment


I'd like to export or replicate a scheme environment in another guile process. The algorithm I'm imagining would do something like this to serialize:

(map (lambda (var val) (display (quasiquote (define ,var ,val))
                       (newline))
     (get-current-environment))

And then I'd read/eval that on the other end.

However, while there are functions that return the current environment, they are in some internal format that I can't just map across. How can I "walk" the environment as the above? Alternatively, how else can I replicate an environment into another process?


Solution

  • you may decompose the so-called "current-environment" like this:

    (define (get-current-binding-list)
            (let* ((e (current-module))  ;; assume checking current-module
    
                   (h (struct-ref e 0))  ;; index 0 is current vars hashtable
                  )
           (hash-map->list cons h)  ;; return a vars binding list
        ))
    

    and you can call (get-current-binding-list) to get variables binding list in current-module. Please note that each element in this list is a pair of symbol and variable type, say, (symbol-name . variable-type). So you may print it like this: for a instance ,you got a var binding:

    (define abc 5)
    

    then:

    (let ((vl (get-current-binding-list)))
          (assoc-ref vl 'abc)
          )
    

    ==> #<variable 9bb5108 value: 5> This result is a "variable type" of variable "abc". You can get it's value with variable-ref procedure.

    So you can trace all the bindings and do something ,in your code ,it's simply print var-name and var-value.

    I know my answer is too brief, but I think there's enough information to help you to find more details in the manual. Hope this will help you.