;; vectors vs. lists ;; ----------------- ;; rand365 : --> number ;; generates a random number between 1 and 365 (define (rand365) (+ 1 (random 365))) ;; cons-rand : number list-of-numbers -> list-of-numbers ;; cons n random numbers (from 1 to 365) onto a list (define (cons-rand n lst) (if (zero? n) lst (cons-rand (- n 1) (cons (rand365) lst)))) ;; rand-list : number --> list-of-numbers ;; given a number n, generates a list of n random numbers between 1 and 365 (define (rand-list n) (cons-rand n empty)) ;; rand-vec : number --> vector-of-numbers ;; given a number n, generates a vector of n random numbers between 1 and 365 (define (rand-vec n) (list->vector (rand-list n))) ;; list-ref : list-of-items number -> item ;; gets the nth item of a list ;; compare with vector-ref (define (list-ref l n) (cond [(empty? l) (error 'list-ref "index out of range")] [(zero? n) (first l)] [else (list-ref (rest l) (- n 1))])) ;; let L be the name of a list of 1000 random numbers between 1 and 365 (define L (rand-list 1000)) ;; let V be a vector version of L (define V (list->vector L)) ;; now let's repeatedly apply list-ref and vector-ref so we can see which ;; is faster: (define (iterate-list n z) (if (zero? n) z (iterate-list (- n 1) (list-ref L 500)))) (define (iterate-vec n z) (if (zero? n) z (iterate-vec (- n 1) (vector-ref V 500)))) ;; to time it we could type: (time (iterate-list 10000 0)) (time (iterate-vec 10000 0))