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 ;product : (listof numbers) -> numbers
5 ;Computes the product of alon0.
7 (define (product alon0)
8 (local ;; the accumulator represents the product of all the numbers preceding alon1 in alon0,
9 ;; ie, it represents the product of (alon1,alon0]
10 ((define (product-accu alon1 accumulator)
12 [(empty? alon1) accumulator]
13 [else (product-accu (rest alon1) (* (first alon1) accumulator))])))
14 (product-accu alon0 1)))
16 (equal? (product '(1 2 3 4 5 6)) 720)
18 ;how-many : (listof X) -> number
19 ;Determines how many items there are in alox0.
21 (define (how-many alox0)
22 (local ;;the accumulator represents the number of items preceding alox1 in alox0
23 ((define (how-many-accu alox1 accumulator)
25 [(empty? alox1) accumulator]
26 [else (how-many-accu (rest alox1) (+ 1 accumulator))])))
27 (how-many-accu alox0 0)))
29 (equal? (how-many '(5 hey joe 5 1 0 true true false)) 9)
31 ;add-to-pi : N -> number
34 (define (add-to-pi n0)
35 (local ;; the accumulator represents n0-n1+pi.
36 ((define (add-to-pi-accu n1 accumulator)
38 [(zero? n1) accumulator]
39 [else (add-to-pi-accu (sub1 n1) (add1 accumulator))])))
40 (add-to-pi-accu n0 pi)))
42 ;add-to-x : N -> number
45 (define (add-to-x n0 x)
46 (local ;; the accumulator represents n0-n1+x.
47 ((define (add-to-x-accu n1 accumulator)
49 [(zero? n1) accumulator]
50 [else (add-to-x-accu (sub1 n1) (add1 accumulator))])))
51 (add-to-x-accu n0 x)))
53 (equal? (add-to-x 5 6) 11)
55 ;make-palindrome : (listof X) -> (listof X)
56 ;Creates a palindrome from alox (non-empty list).
58 (define (make-palindrome alox0)
59 (local ;The accumulator represents the items in alox0 preceding alox1
60 ;in reverse order as in alox0.
61 ((define (make-palindrome-accu alox1 accumulator)
63 [(empty? alox1) empty]
64 [(empty? (rest alox1)) (cons (first alox1) accumulator)]
65 [else (cons (first alox1)
66 (make-palindrome-accu (rest alox1) (cons (first alox1) accumulator)))])))
67 (make-palindrome-accu alox0 empty)))
69 (make-palindrome '(a b c 1 5 3))
71 ;is-prime? : N -> boolean
72 ;Determines if n is a prime number.
74 (define (is-prime? n0)
75 (local ;;accumulator i represents the numbers tested from [2,i) in order to
76 ;;determine if n1 is prime
77 ((define (is-prime?-accu n1 i)
80 [(= (remainder n1 i) 0) false]
81 [else (is-prime?-accu n1 (add1 i))])))
82 (is-prime?-accu n0 2)))