[plt-scheme] Programatically Constructed Symbol Used As An Identifier???

From: Dave Herman (dherman at ccs.neu.edu)
Date: Sat Jun 27 09:24:42 EDT 2009

> Your's and jos example is correct way to do what OP asked and
> I would have used the similar method as your's. I just observed that
> using eval also seems to work  :)  .

The rule of thumb is: Don't use `eval' unless you really know what  
you're doing. And even then, you quite likely don't know what you're  
doing. :)

> I really don't know what top-level-form is , can you give an example
> of top-level-forms and not top-level-forms. I assume it is list of  
> definitions
> or simply all forms which are not nested ,right or wrong?

Ordinarily, you don't need to know the difference between top-level  
variables and lexically nested variables, but `eval' is not able to  
"see" lexically nested variables, so it's one place where you do need  
to know the difference. Roughly, a top-level binding is one that's  
defined at the outermost scope of a module body or at the outermost  
scope of the interactions window.

Here are some examples that demonstrate Grant's point:

*** EXAMPLE 1 ***

;; definitions window
#lang scheme
(define (adder x y) ;; at top-level
   (+ x y))

(define (example1)
   ((eval 'adder) 3 4))

;; interactions window
 > (example1)
7


*** EXAMPLE 2 ***

;; definitions window
#lang scheme
(define (example2)
   (define (adder x y) ;; not at top-level
     (+ x y))
   ((eval 'adder) 3 4))

;; interactions window
 > (example2)
reference to an identifier before its definition: adder


*** EXAMPLE 3 ***

;; definitions window
#lang scheme
(define (example3)
   (define (adder x y) ;; not at top-level
     (+ x y))
   ((eval 'adder) 3 4))

;; interactions window
 > (example3)
reference to an identifier before its definition: adder
 > (define (adder x y) ;; at top-level
     (* x y))
 > (example3)
12

In short: 1) you rarely want to use `eval' for yourself, 2) you even  
more rarely want to recommend it as a solution to someone else's  
problem, especially if you don't fully understand it, and 3) you never  
want to recommend it to a novice.

Dave



Posted on the users mailing list.