120 likes | 214 Views
Lecture 8: Recursion Practice. David Evans http://www.cs.virginia.edu/evans. CS200: Computer Science University of Virginia Computer Science. Simpler Gauss Sum?. (define (insertl lst f stopval) (if (null? lst) stopval (f (car lst)
E N D
Lecture 8: Recursion Practice David Evans http://www.cs.virginia.edu/evans CS200: Computer Science University of Virginia Computer Science
Simpler Gauss Sum? (define (insertl lst f stopval) (if (null? lst) stopval (f (car lst) (insertl (cdr lst) f stopval)))) > (intsto 5) (1 2 3 4 5) > (intsto 1) (1) Same as previous lecture. (define (gauss-sum n) (insertl (intsto n) + 0)) > (gauss-sum 10) 55 (insertl (list 1 2 3 … n) + 0) (+ 1 (+ 2 (+ 3 (+ … (+ n 0))))) CS 200 Spring 2004
Reverse intsto ;;; Evaluates to the list (n n-1 … 3 2 1) ;;; if n >= 1, null if n = 0. > (intsfrom 10) (10 9 8 7 6 5 4 3 2 1) (define (intsfrom n) (if (= n 0) null (cons n (intsfrom (- n 1))))) CS 200 Spring 2004
Intsto? (define (intsto n) (if (= n 0) null (list (intsto (- n 1)) n))) > (intsto 5) (((((() 1) 2) 3) 4) 5) CS 200 Spring 2004
append > (append (list 3) (list 4)) (3 4) > (append (list 3) null) (3) > (append null (list 3)) (3) > (append (list 1 2 3) (list 4 5 6)) (1 2 3 4 5 6) Checkup: Try and define append yourself. CS 200 Spring 2004
Intsto (define (intsto n) (if (= n 0) null (append (intsto (- n 1)) (list n)))) > (intsto 5) (1 2 3 4 5) CS 200 Spring 2004
Using Intsto (define (gauss-sum n) (insertl (intsto n) + 0)) (define (factorial n) (insertl (intsto n) * 1)) CS 200 Spring 2004
map (map f lst) Evaluates to the list of values produced by applying f to each element of lst. CS 200 Spring 2004
map (define (map f lst) (if (null? lst) null (cons (f (car lst)) (map f (cdr lst)))) CS 200 Spring 2004
map (define (map f lst) (insertl lst (lambda (a b) (cons (f a) b)) null)) CS 200 Spring 2004
map examples > (map (lambda (x) x) (intsto 5)) (1 2 3 4 5) > (map (lambda (x) (* x x)) (intsto 5)) (1 4 9 16 25) > (map (lambda (row) (display-one-row output-file row tile-width tile-height)) tiles) Displays a photomosaic! CS 200 Spring 2004
Challenge Problem Define a procedure (define (for index test combine next accum) …) that can be used like this: (define (gauss-sum n) (for 1 (lambda (index) (> index n)) + (lambda (x) (+ 1 x)) 0)) CS 200 Spring 2004