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.
Here’s a simple version, using `vector’s:
That runs in about 250 ms on my machine.
If we switch to using
flvector:Then it runs in about 60 ms.
If we change it to use Typed Racket:
Now it runs in about 20 ms.