[racket] idiomatic and fast

From: Michael W (mwilber at uccs.edu)
Date: Sat Apr 28 18:07:09 EDT 2012

Here's a solution based on for/fold that hasn't been suggested
yet. Runs in O(n) time.

(let-values ([(results last-sum)
              (for/fold ([sofar '()]
                         [value 1])
                  ([i (in-range 2 22)])
                (values (cons value sofar)
                        (+ value i)))])
  (reverse results))

2 hours ago, Joe Gilray wrote:
> Hi,
> 
> I'm trying to come up with the most idiomatic way to generate triangle
> numbers that is also fast:
> 
> (for/list ([i (in-range 2 22)]) (for/sum ([j (in-range i)]) j))
> 
> works but is slow because it regenerates the sums each time
> 
> (define s 0) (for/list ([i (in-range 1 21)]) (set! s (+ s i)) s)
> 
> is fast, but ugly.
> 
> How do I keep the sum in an idiomatic fashion?
> 
> Thanks,
> -Joe

-- 
Take care,
    _mike

Posted on the users mailing list.