How do I get a definition's name as a symbol?

余生长醉 提交于 2021-02-19 08:18:09

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!