简体   繁体   English

球拍阅读器宏

[英]Racket reader macros

Is there any way to make simple reader macros in Racket. 有没有办法在Racket中制作简单的阅读器宏。 I mean a generalization like this: 我的意思是像这样的概括:

(define-reader-syntax "'" quote)
; finds expressions that start with "'" and wraps them in `(quote ...)`
'(foo) ; => (quote (foo))
'foo ; => (quote foo)

I used a built in syntax to make clear what I mean. 我使用内置语法来明确我的意思。 One of the things I'd like to use this for is replicating clojure's shorthand lambda (#(+ 1 %) 5) ; => 6 我想用它做的一件事就是复制clojure的速记lambda (#(+ 1 %) 5) ; => 6 (#(+ 1 %) 5) ; => 6

It seems like it would be very easy to just define a "shorthand-lambda" macro and map the "#" prefix to that. 看起来很容易定义一个“shorthand-lambda”宏并将“#”前缀映射到它。

Here's how to implement your shorthand lambda: 以下是如何实现速记lambda:

#lang racket

(define rt (make-readtable #f #\# 'non-terminating-macro
                           (λ (c in . _)
                             (define body (read in))
                             `(lambda (%) ,body))))
(parameterize ([current-readtable rt]
               [current-namespace (make-base-namespace)])
  (eval (read (open-input-string "(#(+ 1 %) 5)")))) ;; => 6

Here's how to implement your simpler example, making & be equivalent to ' : 以下是如何实现您简单的例子,使得&相当于'

(define rt2 (make-readtable #f #\& #\' #f))

(parameterize ([current-readtable rt2]
               [current-namespace (make-base-namespace)])
  (eval (read (open-input-string "&(3 4 5)")))) ;; => '(3 4 5)

Look at the guide entry on readtables and reader extensions to see how to do this. 只看该引导进入readtables读者的扩展来看看如何做到这一点。 This reference section is useful too. 参考部分也很有用。 Readtable extensions are a bit more complicated than your example, but they are very powerful. 可读扩展比您的示例复杂一点,但它们非常强大。

For your specific problem, SRFI-26 provides a similar syntax for Scheme and Sam Tobin-Hochstadt wrote a fancy app Racket macro that implements Scala's take on this. 针对您的具体问题, SRFI-26为Scheme提供了类似的语法,Sam Tobin-Hochstadt编写了一个花哨的应用程序 Racket宏,它实现了Scala对此的看法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM