From jacobson@math-cs.cns.uni.edu Fri Jan 16 19:20:02 2004 Date: Fri, 16 Jan 2004 19:19:25 -0600 (CST) From: Mark Jacobson To: 810-151-04@uni.edu Subject: [810-151-04] Scheme position in list problem (and factorial too). HERE IS a solution to the position problem. It is an IMPROVED SOLUTION that is more efficient. It requires that you are using the full version of Scheme, not one of the student versions. Welcome to DrScheme, version 204. Language: Textual (MzScheme, includes R5RS). > (position 33 '(22 44 33)) 3 > (member 3 '(1 3 5)) (3 5) > (position 33 '(22 44)) 0 > (position 33 '()) 0 See http://www.cns.uni.edu/~jacobson/scheme/ for earlier version of position. 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 positionLocation (lambda (n li) (if (= n (car li)) 1 (+ (positionLocation n (cdr li)) 1)))) (define position (lambda (n li) (if (member n li) (positionLocation n li) 0))) ******************* FACTORIAL SOLUTION ************************* (define (factorial n) (if (<= n 1) 1 (* n (factorial (- n 1))))) > (factorial 4) 24 > (factorial 5) 120 > (factorial 8) 40320 > (factorial 10) 3628800 > > (factorial 20) 2432902008176640000 ******************* FACTORIAL SOLUTION *************************