[racket] Problem Stream with alternating values

From: Patrick Sweetman (sweetman.p.c at xtra.co.nz)
Date: Sun May 19 15:20:06 EDT 2013

On 19/05/2013 21:22, Jos Koot wrote:
> Your function H1 is not lazy enough.
> Closely following the instructions of the exercise I immediately come with:
> (define (dan-then-dog)
>  (cons "dan.jpg"
>   (lambda () ???)))
> Can you fill in the question-marks?
> Can easily be done with stream-cons too:

Right. I was stuck in the 'C' paradigm of passing everything in the
parameter list, wheras, I think, the stream should only ever be referred
to as the return value from a function call.

I like my original approach, using b0 as a state variable, because it
can be extended to produce a stream of any repeating set of values. The
more concise double stream-cons is not so general.  Fixing the syntax of
my original code gives me:-

(define (dan-then-dog)
  (define (H1 b0)
      [(= b0 1) (stream-cons dan (H1 0))]
      [else     (stream-cons dog (H1 1))]
  (H1 1))

> (define dan-then-dog-str (stream-cons "dan.jpg" ...))
> but this is not according to the exercise, I think. In the exersize a stream
> is defined as a thunk.

I saw that. The requirement for a stream of alternating values was
clearly stated, but then it confusingly talked about the internal
structure of a stream.  Surely if the stream is constructed by stream
primitives then it will all be thunked.  Or do you read the problem as
requiring that the stream itself be separately thunked?


> Jos
>> -----Original Message-----
>> From: users-bounces at racket-lang.org 
>> [mailto:users-bounces at racket-lang.org] On Behalf Of Patrick Sweetman
>> Sent: jueves, 16 de mayo de 2013 14:31
>> To: users at racket-lang.org
>> Subject: [racket] Problem Stream with alternating values
>> I'm doing this problem:
>> 6. Write a stream dan-then-dog, where the elements of the stream
>> alternate between the strings "dan.jpg" and "dog.jpg" (starting with
>> "dan.jpg"). More specically, dan-then-dog should be a thunk that when
>> called produces a pair of "dan.jpg" and a thunk that when called
>> produces a pair of "dog.jpg" and a thunk that when called... 
>> etc. Sample
>> solution: 4 lines.
>> and I cannot for the life of me understand why the following code does
>> not produce a properly thunked stream. It evaluates the 
>> entries until it
>> runs out of memory
>> (define dan "dan.jpg")
>> (define dog "dog.jpg")
>> (define (dan-then-dog)
>>   (define (H1 st0 b0)
>>     (cond
>>       [(= b0 1) (H1 (stream-cons dan st0) 0)]
>>       [else     (H1 (stream-cons dog st0) 1)]
>>       )
>>     )
>>   (H1 empty-stream 1))
>> Can somebody please explain why my understanding of Racket streams is
>> faulty?
>> Thanks,
>> Patrick Sweetman
>> ____________________
>>   Racket Users list:
>>   http://lists.racket-lang.org/users

Posted on the users mailing list.