Download presentation
Presentation is loading. Please wait.
Published byDavid Cristóbal Ortiz Méndez Modified over 6 years ago
1
David Evans http://www.cs.virginia.edu/evans
Lecture 8: Recursion Practice CS200: Computer Science University of Virginia Computer Science David Evans
2
Simpler Gauss Sum? > (intsto 5) (1 2 3 4 5) > (intsto 1) (1)
(define (insertl lst f stopval) (if (null? lst) stopval (f (car lst) (insertl (cdr lst) f stopval)))) > (intsto 5) ( ) > (intsto 1) (1) Same as previous lecture. (define (gauss-sum n) (insertl (intsto n) + 0)) > (gauss-sum 10) 55 (insertl (list … n) + 0) (+ 1 (+ 2 (+ 3 (+ … (+ n 0))))) 2 February 2004 CS 200 Spring 2004
3
Reverse intsto (define (intsfrom n) (if (= n 0) null
;;; Evaluates to the list (n n-1 … 3 2 1) ;;; if n >= 1, null if n = 0. > (intsfrom 10) ( ) (define (intsfrom n) (if (= n 0) null (cons n (intsfrom (- n 1))))) 2 February 2004 CS 200 Spring 2004
4
Intsto? (define (intsto n) (if (= n 0) null
(list (intsto (- n 1)) n))) > (intsto 5) (((((() 1) 2) 3) 4) 5) 2 February 2004 CS 200 Spring 2004
5
append > (append (list 3) (list 4)) (3 4)
> (append (list 3) null) (3) > (append null (list 3)) > (append (list 1 2 3) (list 4 5 6)) ( ) Checkup: Try and define append yourself. 2 February 2004 CS 200 Spring 2004
6
Intsto (define (intsto n) (if (= n 0) null
(append (intsto (- n 1)) (list n)))) > (intsto 5) ( ) 2 February 2004 CS 200 Spring 2004
7
Using Intsto (define (gauss-sum n) (insertl (intsto n) + 0))
(define (factorial n) (insertl (intsto n) * 1)) 2 February 2004 CS 200 Spring 2004
8
map (map f lst) Evaluates to the list of values produced by applying f to each element of lst. 2 February 2004 CS 200 Spring 2004
9
map (define (map f lst) (if (null? lst) null (cons (f (car lst))
(map f (cdr lst)))) 2 February 2004 CS 200 Spring 2004
10
map (define (map f lst) (insertl lst (lambda (a b) (cons (f a) b))
null)) 2 February 2004 CS 200 Spring 2004
11
map examples > (map (lambda (x) x) (intsto 5)) (1 2 3 4 5)
> (map (lambda (x) (* x x)) (intsto 5)) ( ) > (map (lambda (row) (display-one-row output-file row tile-width tile-height)) tiles) Displays a photomosaic! 2 February 2004 CS 200 Spring 2004
12
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)) 2 February 2004 CS 200 Spring 2004
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.