[racket] static variables question

From: Joe Gilray (jgilray at gmail.com)
Date: Sat Feb 18 03:51:23 EST 2012

OK, I read some more and played around and got the behavior I wanted as
follows:

(define primes-from-to
  (let ([lastend 0] [storedlst '()])
    (lambda (start end)
    (cond [(= lastend 0) (set! storedlst (primes-to end))]
          [(= lastend start) (set! storedlst (sieve (append storedlst
(interval-list start end))))]
          [(< lastend end) (primes-from-to lastend end)])

    ; storedlst now has all the primes needed
    (set! lastend end)
    (filter (lambda (v) (if (and (>= v start) (<= v end)) #t #f)) storedlst)
    )))

Now lastend and storedlst are preserved between calls and I get the speed
up I expected:

> (time (primes-from-to 60000 60050))
cpu time: 6630 real time: 6694 gc time: 967
'(60013 60017 60029 60037 60041)
> (time (primes-from-to 60000 60030))
cpu time: 0 real time: 1 gc time: 0
'(60013 60017 60029)

I'd like to understand more about this, if anyone would care to enlighten
me, I'd love to see more examples than I can find in the guide and
reference.

Thanks,
-joe

On Fri, Feb 17, 2012 at 9:05 PM, Joe Gilray <jgilray at gmail.com> wrote:

> I've seen Eli's example of static variables on Stackoverflow, but I still
> need help.
>
> I've created a working sieve and now I want to wrap it in a manner that
> save primes to be used later.
>
> This is what I tried:
>
> ; wrapper function for sieve
> (define (primes-from-to start end)
>   (let ([lastend 0] [storedlst '()])
>     (lambda ()
>     (cond [(= lastend 0) (set! storedlst (primes-to end))]
>           [(= lastend start) (set! storedlst (sieve (append storedlst
> (interval-list start end))))]
>           [(< lastend end) (primes-from-to lastend end)])
>
>     ; storedlst now has all the primes needed
>     (set! lastend end)
>     (filter (lambda (v) (if (and (>= v start) (<= v end)) #t #f))
> storedlst)
>     )))
>
> It works, but I can't get any speed advantages as I simply don't know how
> to syntactically vary start and end and save lastend and storedlst.
>
> (define a (prime-from-to 100 200)) is not useful when I want to later call
> (a 50 70).
>
> I read the manual about all the define* functions but really nothing seems
> to fit, what am I missing?
>
> Thanks,
> -joe
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20120218/88a3703f/attachment.html>

Posted on the users mailing list.