[racket] idiomatic and fast

From: Jordan Johnson (jmj at fellowhuman.com)
Date: Sat Apr 28 18:39:30 EDT 2012

> From: Joe Gilray <jgilray at gmail.com>
> To: Racket mailing list <users at racket-lang.org>
> Subject: [racket] idiomatic and fast
> 
> 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?

How about this:

;; Nat -> Listof[Nat]
;; produces the list of the first n triangle numbers, ascending
(define (list-triangles n)
  (reverse
    (for/fold ([triangles '(1)]) ([i (in-range 2 (+ 1 n))])
      (cons (+ i (first triangles))
            triangles))))

Cheers,
jmj

Posted on the users mailing list.