# Efficient random number list sum in Racket

What would be the most efficient way to first generate and then sum a list of random integers in Racket?

I am trying to implement an equivalent of the code in https://scottlocklin.wordpress.com/2011/11/30/only-fast-languages-are-interesting but I can only come up with slow imlpementations.

My first naive attempt (not random integers, but anyway):

(define (sum-list l) (if (null? l) 0 (+ (first l) (sum-list (rest l))))) (define avector (build-vector 3000000 add1)) (time (sum-list avector))

Please note that the efficient part of the code should only be the actual sum of the list, not the generation.

Thanks a lot.

## Answers

Here's a simple version, using `vector's:

#lang racket (define N 3000000) (define avector (for/vector #:length N ([i (in-range N)]) (random))) (define (sum-vec v) (for/fold ([i 0.0]) ([e (in-vector v)]) (+ e i))) (time (sum-vec avector))

That runs in about 250 ms on my machine.

If we switch to using flvector:

#lang racket (require racket/flonum) (define N 3000000) (define avector (for/flvector #:length N ([i (in-range N)]) (random))) (define (sum-vec v) (for/fold ([i 0.0]) ([e (in-flvector v)]) (+ e i))) (time (sum-vec avector))

Then it runs in about 60 ms.

If we change it to use Typed Racket:

#lang typed/racket (require racket/flonum) (define N 3000000) (define avector (for/flvector #:length N ([i (in-range N)]) (random))) (: sum-vec : FlVector -> Float) (define (sum-vec v) (for/fold ([i 0.0]) ([e (in-flvector v)]) (+ e i))) (time (sum-vec avector))

Now it runs in about 20 ms.