Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Racket reader macros

Is there any way to make simple reader macros in 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

It seems like it would be very easy to just define a "shorthand-lambda" macro and map the "#" prefix to that.

like image 626
adrusi Avatar asked Nov 27 '11 23:11

adrusi


1 Answers

Here's how to implement your shorthand 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)
like image 98
Sam Tobin-Hochstadt Avatar answered Sep 20 '22 06:09

Sam Tobin-Hochstadt