Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
;; make-ints: int -> list-of-ints
;; makes a list of ascending integers from n to 1 or empty if n = 0.
;; Examples:
(check-expect (make-ints 0) empty)
(check-expect (make-ints 1) (list 1))
(check-expect (make-ints 2) (list 1 2))
(check-expect (make-ints 3) (list 1 2 3))

(define (make-ints n)
  (cond
    [(zero? n) empty]
    [(positive? n) 
     (local
       [(define (helper acc i)
          (cond
            [(zero? i) acc]
            [(positive? i) (helper (cons i acc) (sub1 i))]))]
       (helper (list n) (sub1 n)))]))


(define ints (make-ints 1000000))

  ;; reduce this value if you run out of memory intially.
;;max: num num --> num 
;; returns the larger of the two numbers.
;; The following functions both return the largest value in the given list
(time (foldr max 0 ints))  ;; try increasing the size of ints above by factors of 10 until you run out of memory.
(time (foldl max 0 ints))  ;; comment out the foldr line and see if you still run out of memory. 

You should see that the foldl version runs significantly faster than the foldr version. And if you comment out foldr and foldl one at a time, try increasing the size of "ints" by a factor of 10, you will see that foldl runs with much less memory than foldr. Why do you think that I wrote "make-ints" as a forward accumulation algorithm?

...