[racket] Strings as lists

From: Matthias Felleisen (matthias at ccs.neu.edu)
Date: Sat Mar 3 13:00:31 EST 2012

See Ian's reply:

> (for/fold ((sum 0)) ((c "hello world"))
    (+ sum (char->integer c)))

Assuming you have a different goal in mind, here is how to convert the example from the Guide into an example that gives you a tiny bit of what you have in mind. 

;; string-reader-example.rkt:
#reader "string-reader.rkt" #lang racket 
(first "hello")

;; string-reader.rkt:
#lang racket 

(provide (rename-out [$-read read]
                     [$-read-syntax read-syntax]))

(define ($-read in)
  (parameterize ([current-readtable (string-readtable)]) 
    (read in)))

(define ($-read-syntax src in)
  (parameterize ([current-readtable (string-readtable)])
    (read-syntax src in)))

(define read-a-string 
    [(ch in) `(string->list ,(read in))]
    [(ch in src line col pos)
     ;; an awful way of reading a symbol-like string -- do better here
     (define x (read-syntax src in)) (read-char in)
     ;; convert the string into a literat list of chars (via quote)
     `(quote ,(string->list (symbol->string (syntax-e x))))]))

(define (string-readtable)
  (make-readtable (current-readtable) #\" 'terminating-macro read-a-string))

On Mar 3, 2012, at 4:13 AM, Timothy Farland wrote:

> Hi racket folk, lisp neophyte here (just finished HTDP),
> I would like to use Haskell-style strings in my racket, where a string is defined as either '() or (cons character string), and is read from and displayed by values enclosed by double quotes.
> i.e: "string" is understood as '(#\s #\t #\r #\i #\n #\g) and '(#\s #\t #\r #\i #\n #\g) is displayed as "string".
> .. so one could do, for example (car "string") => #\s, or (cdr "string") => "tring" etc.
> I've made altered versions of the basic list processing functions that act differently when given strings or lists, so they achieve this, but at the cost of a lot of runtime checks.
> For a better approach I suspect one would need to deal with the 'reader,' but looking at the documentation, it seems a bit beyond my current understanding. 
> Has anyone else seen or built a language extension that achieves this, or could anyone point me to some next-step resources that will bring me up to the level where I can understand the reader documentation? Or is my enterprise here misguided?
> Many thanks
> -- 
> Tim Farland
> e:twfarland at gmail.com
> ____________________
>  Racket Users list:
>  http://lists.racket-lang.org/users

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20120303/3300bad6/attachment.html>

Posted on the users mailing list.