Search code examples
loadschemeenvironmentmit-scheme

(load "file.scm") in a New Environment in Scheme


MIT Scheme's (load ...) procedure apparently takes in an environment as a parameter. Is there any way I could "clone" the current environment and pass it there, so that I can isolate the file's environment from my own?

(I've looked here but I haven't found anything...)


Solution

  • How about something like this ?

    (define (clone-env env)
      (let ((bindings (environment-bindings env)))
        (make-top-level-environment (map car bindings)
                                    (map cadr bindings))))
    
    1 ]=> (define foo 1)
    
    ;Value: foo
    
    1 ]=> (eq? (the-environment) (clone-env (the-environment)))
    
    ;Value: #f
    

    Edited to add:

    I'm not exactly sure what you are trying to do, but here's what I did to test the above. I created a file foo.scm containing:

    (set! foo 2)
    (define baz (+ foo foo))
    baz
    

    Then,

    1 ]=> (define foo 1)
    
    ;Value: foo
    
    1 ]=> (load "foo.scm" (clone-env (the-environment)))
    
    ;Loading "foo.scm"... done
    ;Value: 4
    
    1 ]=> foo
    
    ;Value: 1
    
    1 ]=> baz
    
    ;Unbound variable: baz
    ;To continue, call RESTART with an option number:
    ; (RESTART 3) => Specify a value to use instead of baz.
    ; (RESTART 2) => Define baz to a given value.
    ; (RESTART 1) => Return to read-eval-print level 1.
    
    2 error>