[racket] streams, recursion and running out of memory

From: Joe Gilray (jgilray at gmail.com)
Date: Mon Feb 20 20:19:02 EST 2012

Hi,

I created an infinite stream of primes (using this interesting article:
http://matthias.benkard.de/journal/116)

I tried to create a prime-pi function:

  (define (prime-pi n)
    (let loop-count ([candidate-stream prime-stream])
      (if (> (stream-first candidate-stream) n)
          0
          (+ (loop-count (stream-rest candidate-stream)) 1))))

(prime-pi 500000) grinds and runs out of memory

But this little cludge makes it run just fine:

  (define (prime-pi n)
    (stream-ref prime-stream (inexact->exact (* 0.1 n)))  ; cludge added to
get the stream to pre-create enough primes
    (let loop-count ([candidate-stream prime-stream])
      (if (> (stream-first candidate-stream) n)
          0
          (+ (loop-count (stream-rest candidate-stream)) 1))))

What am I not understanding?

Thanks,
-Joe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20120220/9cc99acc/attachment-0001.html>

Posted on the users mailing list.