notes04 - and another subproblem for the rest of the...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
Instead of a sequence of events, we have composition of functions, like f ( g ( x )) in high school algebra. We can represent this visually with function machines and plumbing diagrams. Recursion: ;;;;; In file cs61a/lectures/1.1/argue.scm > (argue ’(i like spinach)) (i hate spinach) > (argue ’(broccoli is awful)) (broccoli is great) (define (argue s) (if (empty? s) ’() (se (opposite (first s)) (argue (bf s))))) (define (opposite w) (cond ((equal? w ’like) ’hate) ((equal? w ’hate) ’like) ((equal? w ’wonderful) ’terrible) ((equal? w ’terrible) ’wonderful) ((equal? w ’great) ’awful) ((equal? w ’awful) ’great) ((equal? w ’terrific) ’yucky) ((equal? w ’yucky) ’terrific) (else w) )) This computes a function (the opposite function) of each word in a sentence. It works by dividing the problem for the whole sentence into two subproblems: an easy subproblem for the Frst word of the sentence,
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: and another subproblem for the rest of the sentence. This second subproblem is just like the original problem, but for a smaller sentence. We can take pigl from last lecture and use it to translate a whole sentence into Pig Latin: (define (pigl-sent s) (if (empty? s) () (se (pigl (first s)) (pigl-sent (bf s))))) The structure of pigl-sent is a lot like that of argue . This common pattern is called mapping a function over a sentence. Not all recursion follows this pattern. Each element of Pascals triangle is the sum of the two numbers above it: (define (pascal row col) (cond ((= col 0) 1) ((= col row) 1) (else (+ (pascal (- row 1) (- col 1)) (pascal (- row 1) col) )))) 270...
View Full Document

Ask a homework question - tutors are online