Search code examples
schemer6rs

Print the name of a variable


Is it possible in Scheme R6RS to print the name of a variable? I mean:

(define (f) 
   (lambda (arg)
      (display ( *name* arg))))

Such that:

(define my-var 3)
(f my-var) ; => displays the string "my-var")

Solution

  • You need a syntactic extension (a.k.a. macro) to prevent evaluation:

    #lang r6rs
    (import (rnrs))
    
    (define-syntax f
      (syntax-rules ()
        [(_ x) (display 'x)]))
    
    (define my-var 3)
    (f my-var)
    

    outputs

    my-var
    

    Racket's macro-expander shows the effects of the transformation:

    (module anonymous-module r6rs
      (#%module-begin
       (import (rnrs))
       (define-syntax f (syntax-rules () [(_ x) (display 'x)]))
       (define my-var 3)
       (f my-var)))
    
    ->  [Macro transformation]
    
    (module anonymous-module r6rs
      (#%module-begin
       (import (rnrs))
       (define-syntax f (syntax-rules () [(_ x) (display 'x)]))
       (define my-var 3)
       (display 'my-var)))
    

    which, of course, means that you could simply write

    (display 'my-var)
    

    to get the same result ;-)