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

问题描述 投票:0回答:1

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

例如函数round

1。用法(球拍功能)

( round 1.2 )
-> 1

2。用法(我们的宏)

(round (someStruct arg)) 
-> resultStruct
macros racket
1个回答
0
投票

使用功能

(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"

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

© www.soinside.com 2019 - 2024. All rights reserved.