I need to be able to read user input in scheme for a project. For example, I need to be able to read the string 4 5 * .
. I was implementing it using the (read)
function but it gives an error when it reads a .
. I would use a different symbol but it is specified by the project description. Is there a way to do this?
You cannot use read
to input arbitrary text. The read
procedure is only meant for inputting "S-expressions", a data format that can be used to represent a superset of Scheme source code expressions.
The reason you cannot read a .
via the read
procedure is that a period token has a special role in Scheme source: it is used for dotted pair notation. (C1 . C2)
is the way that the pair of C1
and C2
is written as an S-expression. Note there is a crucial difference between the single pair (C1 . C2)
and the list (C1 C2)
(which is made from two pairs); and yet the only difference between the source text is the presence/absence of a single period.
The dotted pair notation is described in section 6.3.2 of the R5RS .
So, as suggested in the comments on your question by Dan D., you should consider using the read-char
procedure to consume user input text. It described in section 6.6.2 of the R5RS . It may seem counter-intuitive, since read-char
only consumes a single character while read
consumes many characters (and builds a potentially large tree of structured data), but the reality is that you can build your own parser on top of read-char
, by invoking it repeatedly in a loop, as suggested by Dan D.
In fact, some scheme systems implement read
itself by making it a Scheme procedure that invokes read-char
. See for example Larceny's reader source code , where read
will call get-datum
, which calls get-datum-with-source-locations
, which calls read-char
in a number of places.
Alternatively, you might have other ways of reading input from the user. The read-line
procedure is quite common (and its also easy to write on top of read-char
). Or you might look into a Parser-Generator (like the one that generated the source code for Larceny's reader, linked above.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.