Blob


1 ;; The first three lines of this file were inserted by DrScheme. They record metadata
2 ;; about the language level of this file in a form that our tools can easily process.
3 #reader(lib "htdp-advanced-reader.ss" "lang")((modname |31.3|) (read-case-sensitive #t) (teachpacks ((lib "draw.ss" "teachpack" "htdp") (lib "arrow.ss" "teachpack" "htdp") (lib "gui.ss" "teachpack" "htdp"))) (htdp-settings #(#t constructor repeating-decimal #t #t none #f ((lib "draw.ss" "teachpack" "htdp") (lib "arrow.ss" "teachpack" "htdp") (lib "gui.ss" "teachpack" "htdp")))))
4 ;!-1 : N -> number
5 ;Computes the factorial of n using structural recursion.
7 (define (!-1 n)
8 (cond
9 [(zero? n) 1]
10 [else (* n (!-2 (sub1 n)))]))
12 ;!-2 : N -> number
13 ;Computes the factorial of n using an accumulator.
15 (define (!-2 n)
16 (local ;the accumulator represents the product of the natural numbers from (x,n]
17 ((define (!-aux x accumulator)
18 (cond
19 [(zero? x) accumulator]
20 [else (!-aux (sub1 x) (* x accumulator))])))
21 (!-aux n 1)))
24 ;check-time : N N (N -> N) -> true
25 ;To evaluate (f x) t number of times.
27 (define (check-time t x f)
28 (cond
29 [(= t 1) (f x)]
30 [else (check-time (sub1 t) x f))]))
32 ;(time (check-time 1000 10000 !-1))
33 ;(time (check-time 1000 10000 !-2))
35 cpu time: 191024 real time: 192079 gc time: 26418
36 cpu time: 194636 real time: 195881 gc time: 26174