;; The first three lines of this file were inserted by DrScheme. They record metadata ;; about the language level of this file in a form that our tools can easily process. #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"))))) ;product : (listof numbers) -> numbers ;Computes the product of alon0. (define (product alon0) (local ;; the accumulator represents the product of all the numbers preceding alon1 in alon0, ;; ie, it represents the product of (alon1,alon0] ((define (product-accu alon1 accumulator) (cond [(empty? alon1) accumulator] [else (product-accu (rest alon1) (* (first alon1) accumulator))]))) (product-accu alon0 1))) (equal? (product '(1 2 3 4 5 6)) 720) ;how-many : (listof X) -> number ;Determines how many items there are in alox0. (define (how-many alox0) (local ;;the accumulator represents the number of items preceding alox1 in alox0 ((define (how-many-accu alox1 accumulator) (cond [(empty? alox1) accumulator] [else (how-many-accu (rest alox1) (+ 1 accumulator))]))) (how-many-accu alox0 0))) (equal? (how-many '(5 hey joe 5 1 0 true true false)) 9) ;add-to-pi : N -> number ;Adds pi to n. (define (add-to-pi n0) (local ;; the accumulator represents n0-n1+pi. ((define (add-to-pi-accu n1 accumulator) (cond [(zero? n1) accumulator] [else (add-to-pi-accu (sub1 n1) (add1 accumulator))]))) (add-to-pi-accu n0 pi))) ;add-to-x : N -> number ;Adds x to n. (define (add-to-x n0 x) (local ;; the accumulator represents n0-n1+x. ((define (add-to-x-accu n1 accumulator) (cond [(zero? n1) accumulator] [else (add-to-x-accu (sub1 n1) (add1 accumulator))]))) (add-to-x-accu n0 x))) (equal? (add-to-x 5 6) 11) ;make-palindrome : (listof X) -> (listof X) ;Creates a palindrome from alox (non-empty list). (define (make-palindrome alox0) (local ;The accumulator represents the items in alox0 preceding alox1 ;in reverse order as in alox0. ((define (make-palindrome-accu alox1 accumulator) (cond [(empty? alox1) empty] [(empty? (rest alox1)) (cons (first alox1) accumulator)] [else (cons (first alox1) (make-palindrome-accu (rest alox1) (cons (first alox1) accumulator)))]))) (make-palindrome-accu alox0 empty))) (make-palindrome '(a b c 1 5 3)) ;is-prime? : N -> boolean ;Determines if n is a prime number. (define (is-prime? n0) (local ;;accumulator i represents the numbers tested from [2,i) in order to ;;determine if n1 is prime ((define (is-prime?-accu n1 i) (cond [(= n1 i) true] [(= (remainder n1 i) 0) false] [else (is-prime?-accu n1 (add1 i))]))) (is-prime?-accu n0 2))) (and (is-prime? 2) (is-prime? 3) (not (is-prime? 4)) (is-prime? 5) (not (is-prime? 6)) (is-prime? 7))