what environment does `eval` execute in? (scheme)
scheme
Solution
You should not need to use `eval` until you are a few years into your Scheme career. By that I mean, many beginners incorrectly believe that `eval` is needed but it generally is not.
For your example, `eval` takes an optional second argument which is the `environment`. If you don't provide the second argument, then the default is `(interaction-environment)`. So, your `myFunc` defines a local variable `a` (the argument to `lambda`) and returns the value for `a` in the interaction environment.
The first time you invoke `(myFunc 1)` there is no `a` in the interaction environment. Then you add `a`, bound to `2`, so the next time you invoke `(myFunc <anynumber>)` you get `a` in the interaction environment, which is `2`
Your definition for `myFunc` is not idiomatic. If you really want a function that returns the value of a defined variable use:
(define myFunc
(lambda (ignore)
a))
> (define a 2)
> (myFunc 1234567)
2
> (set! a 10)
> (myFunc -9876)
10
Problem
I have the following `myFunc` function, the body of which is just an `eval` statement. Could anyone tell me why `eval` is NOT seeing `a`? Or a broader question would be, where do the arguments to `eval` get evaluated? ``` (define myFunc (lambda (a) (eval 'a))) (myFunc 1) ; <<<< this causes undefined var error, WHY? ; define a var named a in the global (define a 2) (myFunc 2) ; <<<<< this returns 2, WHY? ```