[racket] reference #:when clause in for/list?

From: Daniel Prager (daniel.a.prager at gmail.com)
Date: Sun Aug 17 07:17:38 EDT 2014

Hi Mark

Two ideas:

   1. add a bit of state with for/list to save a reference to the expensive
   2. filter-map keeps the reference more localised


#lang racket
(require math/number-theory)

(define (mersenne-primes n)
  (let ([c 'dummy])
    (for/list ([i n]
               #:when (begin
                        (set! c (sub1 (expt 2 i)))
                        (prime? c)))
      (list i c))))

(define (mersenne-primes-2 n)
  (filter-map (λ (i)
                (let ([c (sub1 (expt 2 i))])
                  (and (prime? c)
                       (list i c))))
              (range n)))

(mersenne-primes 128)
(mersenne-primes-2 128)


On Sun, Aug 17, 2014 at 7:03 PM, Mark Wallace <lotabout at gmail.com> wrote:

> Consider the following pseudocode:
> (for/list ([i ...]
>            #:when <very complecated expr E>)
>   <reference to the above expr E>)
> Can I bind that expression E and reference in the body of "for/list"?
> If expression E takes lots of time to finish, we would not want to compute
> it again :).
> I understand that there are workarounds like first collect all items of
> expression E and then use 'filter' to get interested items. However it
> would be a waste of memory if the number of interested items is small.
> So, any ideas?
> --
> Best Regards,
> Mark Wallace.
> ____________________
>  Racket Users list:
>  http://lists.racket-lang.org/users
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20140817/5f187d11/attachment.html>

Posted on the users mailing list.