From jacobson@math-cs.cns.uni.edu Wed Jan 14 11:09:07 2004 Date: Wed, 14 Jan 2004 10:38:05 -0600 (CST) From: Mark Jacobson To: 810-151-04@uni.edu Subject: [810-151-04] Rewrite position, write factorial in Scheme... Hi Scheme students, For Friday, try to think about and do the following three problems: 1. Implement the factorial function in Scheme. n factorial = 1 when n <= 1 n factorial = n * (n - 1) factorial when n > 1. 2. Rewrite the position definition we implemented in class today so that it returns: (position 22 '(11 22 33 44)) returns 2 (position 11 '(11 22 33 44)) returns 1 (position 44 '(11 22 33 44)) returns 4 (position 88 '(11 22 33 44)) returns 0 (Zero indicates 88 is not found in the list). (define (position n l) <---- Assumes n is in list l (if (= n (first l)) 0 and returns positions in range (+ (position n (rest l)) 1))) 0, 1, 2, 3, ... (listlength - 1) Here is the distance Scheme definition we did in class today. Note that the solution could also use cadr or last to get the values of the y coordinates of the two points: p1 = (x1 y1) p2 = (x2 y2) (last p1) same as (cadr p1) same as (car (cdr p1) --------- --------- ------------- (define (distance p1 p2) (sqrt (+ (expt (- (car p1) (car p2)) 2) (expt (- (car (cdr p1)) (car (cdr p2))) 2)))) > (distance '(0 0) '(2 3)) #i3.605551275463989 <----- 3.6055 is the distance... > (distance '(0 0) '(3 4)) 5 <----- 5 is the distance 3. Type in the following and try out the birthday problem. (define (randomListBirthdays n) (if (= n 0) '() (cons (random 365) (randomListBirthdays (- n 1))))) > (randomListBirthdays 5) ??? > (randomListBirthdays 10) ??? > (randomListBirthdays 23) ??? > (cons 222 '(11 33 44)) (list 222 11 33 44) > (cons 100 '(200 300 400)) (list 100 200 300 400) > (random 100) 26 > (random 100) 68 See you on Friday. Mark