是否可以定义一个与球拍中的函数同名的宏,但不能覆盖它。 (因此,根据所传递的参数,该名称将有两种可能的用法)
例如函数round。
1。用法(球拍功能)
( round 1.2 )
-> 1
2。用法(我们的宏)
(round (someStruct arg))
-> resultStruct
(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"
选择您喜欢的人。我怀疑您实际上是要使用函数而不是宏。