Вопрос

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")
Это было полезно?

Решение

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

Другие советы

Let's see how the expression (f my-var) is evaluated. First, note that is an application. Applications evaluate all sub-expressions in some order (in standard Scheme it is undefined, but most Scheme implementation use left-to-right). That is the expression f is evaluated giving a value v1 representing (lambda () (lambda (arg) (display (*name* arg))). The my-var is evaluated giving the value 3. Now v1 is applied to 3.

So the problem here is that the function never sees the variable name my-var, it only sees the result of evaluating it, 3.

The answer to your question must therefore be "no".

But it might that there is an alternative solution. What did you need it for - debugging?

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top