Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

string -> code

35 views
Skip to first unread message

Peter Keller

unread,
Aug 3, 2008, 3:04:55 AM8/3/08
to
Hello,

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

Nils M Holm

unread,
Aug 3, 2008, 6:15:44 AM8/3/08
to
Peter Keller <psi...@merlin.cs.wisc.edu> wrote:
> 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?

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/

Abdulaziz Ghuloum

unread,
Aug 3, 2008, 12:34:56 PM8/3/08
to
Peter Keller wrote:
> Hello,
>
> 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?
> [example]

> Relatedly, is there an easy way to have a port read/write from a string?

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,,,

Jay Reynolds Freeman

unread,
Aug 3, 2008, 1:34:33 PM8/3/08
to
On Aug 3, 12:04 am, Peter Keller <psil...@merlin.cs.wisc.edu> wrote:

> 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.

Peter Keller

unread,
Aug 3, 2008, 1:49:57 PM8/3/08
to
Hello,

These were all awesome answers and out of them I can make my solution.

Thank you very much. I appreciate it!

-pete

0 new messages