From jacobson@math-cs.cns.uni.edu Fri Jan 16 10:46:12 2004 Date: Fri, 16 Jan 2004 10:12:43 -0600 (CST) From: Mark Jacobson To: 810-151-04@uni.edu Subject: [810-151-04] makeSet handout and position solution - class #3 Scheme students, Here is makeSet and makeSet2 programs you received as a handout today in Friday's class: (define makeSet (lambda (li) (if (null? li) li (if (member (car li) (cdr li)) (makeSet (cdr li)) (cons (car li) (makeSet (cdr li))))))) (define makeSet2 (lambda (li) (cond ((null? li) li) ((member (car li) (cdr li)) (makeSet2 (cdr li))) (else (cons (car li) (makeSet2 (cdr li))))))) Note that the two solutions should be compared as you study this so you understand both nested if statements and the cond expression. syntax: (if test consequent alternative) syntax: (cond clause1 clause2 ...) Each clause uses the 2nd of the 3 forms shown below. (test) (test exp1 exp2 ...) <------ makeSet uses this format (test => exp) The last clause may be in either of the above forms or it may be an "else clause" of the form (else exp1 exp2 ...) Welcome to DrScheme, version 205. Language: Textual (MzScheme, includes R5RS). > (makeSet '(M I S S I S S I P P I)) (m s p i) > (makeSet '(11 22 33 44 11 55 66 77 77 88 22)) (33 44 11 55 66 77 88 22) > (makeSet2 '(1 1 1 2 2 3 2 2 2 2 1)) (3 2 1) HERE IS THE solution to the position problem where the position is returned as 0 if n is not in list li, or is returned as 1 for first, 2 for 2nd, 3 for 3rd, etc. (define position2 (lambda (n li) (cond ((null? li) 0) ((= n (car li)) 1) (else (+ (position2 n (cdr li)) 1))))) (define position (lambda (n li) (if (member n li) (position2 n li) 0))) > (position 33 '(11 22 33 44 55)) 3 > (position 33 '()) 0 > (position 77 '(11 22 33 44 55)) 0 > (position 77 '(11 22 33 44 55 66 77)) 7 See you next Wednesday. I will email and post an assignment on the web page sometime later today. Mark