[racket] Help re-writing a function recursively

From: Peter Breitsprecher (pkbreits at lakeheadu.ca)
Date: Tue Nov 16 07:58:28 EST 2010

I know I am missing something small, but I made that change, and it is
terminating too soon, and not quite working correctly.  The nested list
works fine, but the outer list isn't correct.
Example.
I give it input of '(3 (4 5) 6))
and it returns
(((4 5) 3))

Which means it is terminating too soon, and it is reversing the inner list
properly, but not the outer list after it completes that inner recursion.

On 15 November 2010 21:13, YC <yinso.chen at gmail.com> wrote:

>
> On Mon, Nov 15, 2010 at 5:51 PM, Peter Breitsprecher <
> pkbreits at lakeheadu.ca> wrote:
>
>> I am not near my compiler right now, but what if I just made this
>> modification...
>>
>> (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 #\space)) (read-list-helper list-so-far)]
>>             [(eq? next-char #\() (cons (read-list-helper '())
>> list-so-far)
>>             [(eq? next-char #\) (reverse list-so-far)])))
>> (read-list-helper '()))
>>
>> Wouldn't that just create an inner list if it finds a open bracket, and
>> then reverse that list and exit out of that part of it if it finds a closed
>> bracket?
>
>
> Correct - that's the idea for reading in a nested list, unless you were
> trying to flatten the list as you read them.
>
> The (cons (read-list-helper '() list-so-far) should also be passed again to
> your helper proc, or it terminates prematurely.
>
> You might also want to add a test to see if you are at the end of the the
> port, via eof-object?.
>
> Also - your chr is not used in your proc.  If that's the input-port you
> will want to pass it to peek-char and read-char, otherwise they are read
> from current-input-port.
>
> Let's add back the mailing list if you have additional questions, so others
> might chime in.
>
> HTH.  Cheers,
> yc
>
>


-- 
Kurt Breitsprecher
(807) 474-9601
pkbreits at lakeheadu.ca
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20101116/ba73c367/attachment.html>

Posted on the users mailing list.