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.


Need Your Help

How can I grep complex strings in variables?

bash variables grep if-statement

I am trying to grep for a small string in a much larger string. Both strings are being stored as variables and here is a code example:

int / float to NSString without using alloc?

objective-c cocoa

Is there anyway to get int (or float) numbers into a NSString object without using alloc and a subsequent release?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.