Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating list of million random elements

Tags:

scheme

How to efficiently generate a list of million random elements in scheme? The following code hits maximum recursion depth with 0.1 million itself.

(unfold (lambda(x)(= x 1000000)) (lambda(x)(random 1000)) (lambda(x)(+ x 1)) 0)
like image 790
Fakrudeen Avatar asked Dec 04 '22 13:12

Fakrudeen


2 Answers

It really depends on the system you're using, but here's a common way to do that in plain scheme:

(let loop ([n 1000000] [r '()])
  (if (zero? n)
    r
    (loop (- n 1) (cons (random 1000) r))))

One note about running this code as is: if you just type it into a REPL, it will lead to printing the resulting list, and that will usually involve using much more memory than the list holds. So it's better to do something like

(define l ...same...)

There are many other tools that can be used to varying degrees of convenience. unfold is one of them, and another is for loops as can be found in PLT Scheme:

(for/list ([i (in-range 1000000)]) (random 1000))
like image 178
Eli Barzilay Avatar answered Jan 15 '23 12:01

Eli Barzilay


I don't know much scheme but couldn't you just use tail-recursion (which is really just looping) instead of unfold (or any other higher-order function)?

like image 42
PeterM Avatar answered Jan 15 '23 10:01

PeterM