(load “file.scm”) in a New Environment in Scheme

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-23 13:07:42

问题


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...)


回答1:


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>


来源:https://stackoverflow.com/questions/5335595/load-file-scm-in-a-new-environment-in-scheme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!