[racket] I just can't understand readtables

From: Jens Axel Søgaard (jensaxel at soegaard.net)
Date: Mon Apr 29 17:12:19 EDT 2013

Hi,

2013/4/29 Tomás Coiro <tomcoiro at hotmail.com>

> I'm trying to wrap my head around them and be able to use them.
> I'm trying to write something for a Clojure compability layer in Github
> and i just find it impossible to use the make-readtable procedure to start
> doing something.
>
>
> Can someone show me the code to make this #"hello" expand to (regexp
> "hello") ?
>

Here is one way to read #"hello" as (regexp "hello").

#lang racket

(define (read-until port ch)
  (list->string
   (for/list ([c (in-port read-char port)]
              #:break (eqv? c ch))
     c)))

;; A syntax object that has the "original?" property:
(define orig-stx (read-syntax #f (open-input-string "dummy")))

(define (lex# default-rt)
  (case-lambda
    [(ch port) ((lex# default-rt) ch port #f #f #f #f)]
    [(ch port src line col pos)
     (match  (peek-char port)
       [#\"  (read-char port)
             (define str (read-until port #\"))
             (define len (+ (string-length str) 3)) ; #"" is 3 characters
             (define srcloc (vector src line col pos len))
             (datum->syntax #f (regexp str) srcloc orig-stx)]
       [else
        (read-syntax/recursive src port #\# default-rt)])]))

(define (extend-readtable rt)
  (make-readtable rt #\# 'terminating-macro (lex# rt)))

(parameterize
    ([current-readtable (extend-readtable (current-readtable))])
  (read-syntax 'foo (open-input-string "(1 2 #\"foo\" 3 4 #hash() )")))

Note that if we modify the readtable entry for # then we need
to handle all cases beginning with #. In lex# everything by #" is
handled by the old readtable.

-- 
Jens Axel Søgaard
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20130429/82275f1c/attachment-0001.html>

Posted on the users mailing list.