Lecture 8: Recursion Practice CS200: Computer Science University of Virginia Computer Science David Evans http://www.cs.virginia.edu/evans Simpler Gauss Sum? > (intsto 5) (1 2 3 4 5) > (intsto 1) (1) (define (insertl.

Download Report

Transcript Lecture 8: Recursion Practice CS200: Computer Science University of Virginia Computer Science David Evans http://www.cs.virginia.edu/evans Simpler Gauss Sum? > (intsto 5) (1 2 3 4 5) > (intsto 1) (1) (define (insertl.

Lecture 8:
Recursion
Practice
CS200: Computer Science
University of Virginia
Computer Science
David Evans
http://www.cs.virginia.edu/evans
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))))
Same as previous lecture.
(insertl (list 1 2 3 … n) + 0)
(define (gauss-sum n)
(insertl (intsto n) + 0))  (+ 1
(+ 2
(+ 3
(+ …
(+ n 0)))))
> (gauss-sum 10)
55
2 February 2004
CS 200 Spring 2004
2
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)))))
2 February 2004
CS 200 Spring 2004
3
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
4
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.
2 February 2004
CS 200 Spring 2004
5
Intsto
(define (intsto n)
(if (= n 0)
null
(append (intsto (- n 1)) (list n))))
> (intsto 5)
(1 2 3 4 5)
2 February 2004
CS 200 Spring 2004
6
Using Intsto
(define (gauss-sum n)
(insertl (intsto n) + 0))
(define (factorial n)
(insertl (intsto n) * 1))
2 February 2004
CS 200 Spring 2004
7
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
8
map
(define (map f lst)
(if (null? lst)
null
(cons (f (car lst))
(map f (cdr lst))))
2 February 2004
CS 200 Spring 2004
9
map
(define (map f lst)
(insertl lst
(lambda (a b)
(cons (f a) b))
null))
2 February 2004
CS 200 Spring 2004
10
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!
2 February 2004
CS 200 Spring 2004
11
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
12