[racket] Help re-writing a function recursively

From: YC (yinso.chen at gmail.com)
Date: Mon Nov 15 20:17:06 EST 2010

On Mon, Nov 15, 2010 at 4:17 PM, Peter Breitsprecher
<pkbreits at lakeheadu.ca>wrote:

> I have a program that is a simple reader.  Reads the user input character
> by character, and then creates a list of values.  Right now it only works
> with numbers, but i will add functionality for reading characters.  Right
> now it will work, and just accept the numbers and create the list which is
> great, but It won't work for nested lists at all.  I don't think it should
> be that difficult to modify it, but it is proving to be harder than I
> anticipated.
>
> (define (read-list chr)
>   (define (read-list-helper list-so-far)
>      (let ((next-char (peek-char))
>            (this-char (read-char)))
>            (cond [(char-numeric? next-char)(read-list-helper (cons
> this-char list-so-far))]
>             [(or (eq? next-char #\')
>                  (eq? next-char #\))
>                  (eq? next-char #\()
>                  (eq? next-char #\space)) (read-list-helper list-so-far)]
>             [(reverse list-so-far)])))
> (read-list-helper '()))
>


What you want is (cons (read-list-helper '()) list-so-far) where you are
trying to recursively parse the nested list.  And for that you will need to
separate the checking of #\( from #\space and #\).  #\( starts the nest,
skip #\space, and #\) returns from the current nesting.

Note you'll need additional logic if you want to parse multiple numeric
characters as a single number as well.

HTH. Cheers,
yc
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20101115/95dc6033/attachment.html>

Posted on the users mailing list.