2

I am just hacking around with Scheme (mit-scheme) and I have just figured out how you change the environment, so that '+' becomes a symbol for the equivalent procedure of the '-' operator.

Example

(environment-define user-initial-environment '+ -)
(eval (+ 3 2) user-initial-environment)
=> 1

I was just wondering if there were a simple way to deal with environments as variables so when I input an environment into eval, like so

(eval <exp> user-initial-environment) 

I don't have to use 'user-initial-environment'. So I can 'play' with different environments for a function.

(eval <exp> env) 

Where env is some predefined environment attached to my variable 'env'.

Eli Barzilay
  • 29,301
  • 3
  • 67
  • 110
jones
  • 361
  • 1
  • 4
  • 13

1 Answers1

3

The relevant MIT Scheme documentation page on top-level environments could be instructive -- you can either extend an existing top-level environment (with extend-top-level-environment) or make a new one from scratch (with make-top-level-environment).

For evaluating anything but the most trivial expressions, though, it might be instructive to extend either system-global-environment or user-initial-environment (cf 13.2: Environment Variables)

michel-slm
  • 9,438
  • 3
  • 32
  • 31
  • Thankyou, I found my answer! For the record – jones Aug 18 '11 at 17:39
  • Thanks! For the record I went `(define env (make-top-level-environment))` and then went `(environment-define env '+ -)` then `(eval '(+ 2 2) env)` returned `0` and `(eval '(+ 2 2) user-initial-environment)` returned `4`. Interestingly `(eval (+ 2 2) env)` returned 4, and yet mit-scheme's 'eval' requires you to specify two arguments an expression to be evaluated and an environment! Why they don't just allow one argument as input to eval when evidently the second argument is superfluous when you enter the first argument unquoted. – jones Aug 18 '11 at 17:46
  • 3
    ``eval`` is just a function, so actually ``(eval (+ 2 2) env)`` -> ``(eval 4 env)`` so no matter what environment you pass, it will not make a difference; the expression is evaluated in the current environment, *and* its result passed to ``eval`` which will have nothing more to evaluate – michel-slm Aug 18 '11 at 18:19