问题
How do I get a definition's name as a symbol in Scheme and/or Racket? Suppose I have these definitions:
(define bananas 123)
(define multiply *)
(define (pythagoras a b)
(sqrt (+ (* a a) (* b b))))
How can I define def->symbol
where:
(def->symbol bananas)
returns'bananas
(def->symbol multiply)
returns'multiply
(def->symbol pythagoras)
returns'pythagoras
Is this a case where I have no choice but to learn and use these advanced things called "macros"?
回答1:
Just as you suspect, we need to use a macro - and a very simple one! A normal procedure wouldn't work because the parameters get evaluated before calling the procedure, but with a macro we can manipulate the parameters before they get evaluated, and in this case quoting the parameter is all we need to do. In Racket, this is how we'd write it:
(define-syntax-rule (def->symbol def)
'def)
Which is shorthand for Scheme's standard macro syntax:
(define-syntax def->symbol
(syntax-rules ()
((_ def) 'def)))
Either way, it works as expected:
(def->symbol bananas) ; 'bananas
(def->symbol multiply) ; 'multiply
(def->symbol pythagoras) ; 'pythagoras
来源:https://stackoverflow.com/questions/65050604/how-do-i-get-a-definitions-name-as-a-symbol