I have a problem where I have a string filled with scheme code that I'd
like to convert to a list representation. What's the best way to do this
in R5RS?
An example is:
Turn:
"(cons 'foo 42)"
into
'(cons 'foo 42)
Relatedly, is there an easy way to have a port read/write from a string?
Thank you.
-pete
This code may get you started:
http://www.t3x.org/nss/read-from-string.html
--
Nils M Holm <n m h @ t 3 x . o r g> -- http://t3x.org/nmh/
Yes. Most implementations have string input ports and string
output ports. In R6RS, there is open-string-input-port that
does what you want:
> (read (open-string-input-port "(cons 'foo 42)"))
(cons 'foo 42)
SRFI-6, if supported by your implementation, provides the
procedure open-input-string, which does the same thing.
In plain R5RS, you have to implement your own parser, which
is what Nils did. Such parsers are usually incomplete,
handling only a small subset of the Scheme datum syntax
(due to the complexity of the datum syntax) and perform
little or no error checking. Using string ports is a better
choice (unless your goal is learning about parsers).
Aziz,,,
> I have a problem where I have a string filled with scheme code that I'd
> like to convert to a list representation. What's the best way to do this
> in R5RS?
One sneaky way is to "display" your string into a temporary file, then
read from that file:
(let ((my-port (open-output-file "Foo")))
(display "(cons 'foo 42)" my-port)
(close-output-port my-port))
(let* ((my-port (open-input-file "Foo"))
(answer (read my-port)))
(close-input-port my-port)
answer)
==> (cons (quote foo) 42)
Doing it this way leverages the parser that is built into your Scheme
implementation, at the expense of doing some I/O.
These were all awesome answers and out of them I can make my solution.
Thank you very much. I appreciate it!
-pete