;;; File: ;;; exam1.scm ;;; Author: ;;; Samuel A. Rebelsky ;;; The students of CSC153 2004S ;;; Summary: ;;; Assorted notes on exam 3. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Problem 1 ; ;;;;;;;;;;;;; ;;; Procedure: ;;; number->digits ;;; Parameters: ;;; num, a non-negative integer ;;; Purpose: ;;; Compute the digits in num. ;;; Produces: ;;; digits, a list of the form (d_k d_(k-1) ... d_3 d_2 d_1) ;;; Preconditions: ;;; [See above] ;;; Postconditions: ;;; "digits" is the digits of num in order. ;;; d_i = (mod (quotient num (expt 10 (- i 1)) 10) ;;; d_k is nonzero ;;; Each of d_i is in the range [0..9] (define digits->number (lambda (lst) (let kernel ((stuff (reverse lst)) (base 1)) (if (null? stuff) 0 (+ (* base (car stuff)) (kernel (cdr stuff) (* base 10))))))) (define number->digits (lambda (val) (map (lambda (x) (string->number (string x))) (string->list (number->string val))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Problem 2 ; ;;;;;;;;;;;;; ;;; Procedure: ;;; alphabetically-first ;;; Parameters: ;;; str1, str2, ... strk, 1 or more strings ;;; Purpose: ;;; To find the parameter string that comes alphabetically ;;; first. ;;; Produces: ;;; smallest, a string ;;; Preconditions: ;;; [standard] ;;; Postconditions: ;;; (string-ci<=? smallest stri) for all reasonable i. (define alphabetically-first (lambda lst (cond ((null? (cdr lst)) (car lst)) ((null? (cddr lst)) (if (string-ci (value->string (list 'a 'b 'c)) ; "(a b c)" ; > (value->string (list "a" "b" "c")) ; "(\"a\" \"b\" \"c\")" ; > (display (value->string (list "a" "b" "c"))) ; ("a" "b" "c") ; > (value->string (list #\a #\b #\c)) ; "(\#a \#b \#c)" ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Problem 4 ; ;;;;;;;;;;;;; ;;; Procedure: ;;; lookup ;;; Parameters: ;;; name, a string ;;; collection, a list of three-element lists ;;; Purpose: ;;; Find all entries in the catalog with certain last name ;;; Produces: ;;; matches, a list of three-element lists representing all ;;; of the matching entries ;;; Preconditions: ;;; name is a string [unverified] ;;; collection is a valid list of three-element lists ;;; Postconditions: ;;; matches contains all elements of collection for which ;;; it is true that (string=? name (car element)) (define lookup (lambda (name collection) (letrec ((validcollection? (lambda (collection) (if (list? collection) (if (null? (cdr collection)) (if (list? (car collection)) (if (= (length (car collection)) 3) #t #f) #f) (if (list? (car collection)) (if (= (length (car collection)) 3) (validcollection? (cdr collection)) #f) #f))))) (find (lambda (name collection) (if (null? collection) null (if (string=? name (car (car collection))) (cons (car collection) (find name (cdr collection))) (find name (cdr collection))))))) (if (validcollection? collection) (find name collection) (error "Invalid collection")))))