如何获得定义的名称作为符号? [英] How do I get a definition's name as a symbol?

查看:44
本文介绍了如何获得定义的名称作为符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Scheme 和/或 Racket 中将定义的名称作为符号获取?假设我有这些定义:

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

我如何定义 def->symbol 其中:

  • (def->symbol Bananas) 返回 'bananas
  • (def->symbol multiply) 返回 'multiply
  • (def->symbol pythagoras) 返回 'pythagoras
  • (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"?

推荐答案

正如您所怀疑的,我们需要使用 - 一个非常简单的宏!一个正常的过程是行不通的,因为参数在调用过程之前被评估,但是使用宏我们可以在它们被评估之前操作参数,在这种情况下,我们只需要引用参数做.在 Racket 中,我们是这样写的:

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)

这是 Scheme 标准宏语法的简写:

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

这篇关于如何获得定义的名称作为符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆