emacs.d/clones/colinallen.dnsalias.org/lp/node63.html

60 lines
2.4 KiB
HTML

<!DOCTYPE HTML PUBLIC "-//W3O//DTD W3 HTML 2.0//EN">
<!Originally converted to HTML using LaTeX2HTML 95 (Thu Jan 19 1995) by Nikos Drakos (nikos@cbl.leeds.ac.uk), CBLU, University of Leeds >
<HEAD>
<TITLE> Converting Strings to Lists</TITLE>
</HEAD>
<BODY>
<meta name="description" value=" Converting Strings to Lists">
<meta name="keywords" value="lp">
<meta name="resource-type" value="document">
<meta name="distribution" value="global">
<P>
<BR> <HR>
<A HREF="node64.html"><IMG ALIGN=BOTTOM ALT="next" SRC="next_motif.gif"></A>
<A HREF="node58.html"><IMG ALIGN=BOTTOM ALT="up" SRC="up_motif.gif"></A>
<A HREF="node62.html"><IMG ALIGN=BOTTOM ALT="previous" SRC="previous_motif.gif"></A> <BR>
<A HREF="lp.html"><B>Contents</B></A>
<B> Next:</B>
<A HREF="node64.html"> Functions and Lambda Expressions, </A>
<B>Up:</B>
<A HREF="node58.html"> Input and Output</A>
<B> Previous:</B>
<A HREF="node62.html"> Input and Output </A>
<BR> <HR> <P>
<H1> Converting Strings to Lists</H1>
<P>
Sometimes it is useful to convert text strings to lists. For example, to get substantial input, read-line is most convenient, but it returns a string. If the objective is to parse the input, it is much more convenient to have a list of words than a string.
<P>
Here is an example of code to convert a string to a list:
<P>
<BLOCKQUOTE>
<PRE>(defun string-to-list (str)
(do* ((stringstream (make-string-input-stream str))
(result nil (cons next result))
(next (read stringstream nil 'eos)
(read stringstream nil 'eos)))
((equal next 'eos) (reverse result))))
&gt; (string-to-list &quot;this is a string of text&quot;)
(THIS IS A STRING OF TEXT)
</PRE>
</BLOCKQUOTE>
Because of its reliance on read, this function will not work with certain kinds of punctuation. For example:
<P>
<BLOCKQUOTE>
<PRE>&gt; (string-to-list &quot;Commas cause problems, see&quot;)
Error: A comma has appeared out of a backquote.
Error signalled by READ.
Broken at READ. Type :H for Help.
</PRE>
</BLOCKQUOTE>
If punctuation is likely to appear in input, then it is necessary to use read-char, which reads one character at a time. It is then possible to inspect each character and process it appropriately if it is problematic. Exactly how to do this will not be covered here as it makes a nice exercise to develop your understanding of Lisp input processing.
<P>
<BR> <HR>
<P>
<ADDRESS>
<I>&#169; Colin Allen &amp; Maneesh Dhagat <BR>
March 2007 </I>
</ADDRESS>
</BODY>