与基本功能同名的球拍宏功能

萨萨德

是否可以定义一个与球拍中的函数同名但不能覆盖的宏。(因此,该名称将有两种可能的用法,具体取决于传递的参数)

例如功能回合

1.用法(球拍功能)

( round 1.2 )
-> 1

2.用法(我们的宏)

(round (someStruct arg)) 
-> resultStruct
Sorawee Porncharoenwase

使用功能

(require (only-in racket [round @round]))
(define (my-round v)
  ;; do whatever you want to do here
  "hello")

(define (round v)
  (cond
    [(number? v) (@round v)]
    [else (my-round v)]))

(define x 1.2)
(round x) ;=> 1.0
(define y "abc")
(round y) ;=> "hello"

通过定义round为函数,案例分析将在运行时传递给函数进行

使用宏

(require syntax/parse/define 
         (only-in racket [round @round]))

(define-syntax-parser round
  [(_ x:number) #'(@round x)]
  [(_ x) #'"hello"])

(define x 1.2)
(round x) ;=> "hello"
(define y "abc")
(round y) ;=> "hello"
(round 1.2) ;=> 1.0
(round (this is not a sensible expression but it works (()))) ;=> "hello"

通过定义round为宏,可以对编译时传递给宏语法片段进行大小写分析在上面的示例中,当宏的操作数为文字数时,我们将使用实际的拍子数。其他所有内容都将转换为请注意,在编译时,像这样的标识符尚未评估并且尚未与值关联。您唯一知道的是它是一个标识符,而不是文字数字,因此它转换为宏扩展后的该程序大致为:round"hello"x"hello"

(require syntax/parse/define 
         (only-in racket [round @round]))

(define x 1.2)
"hello"
(define y "abc")
"hello"
(@round 1.2)
"hello"

选择您喜欢的那个。我怀疑您实际上是要使用函数而不是宏。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章