110 likes | 123 Views
Discover the essence of recursion in programming, its various applications in functions like mapping, counting, finding, and more. Learn about different recursion patterns, like tree recursion and advanced concepts such as Pascal’s Triangle. Dive into practical examples and challenges to enhance your understanding of recursion.
E N D
Midterm 1 • You did great • If you need a regrade, see the person that graded that question • Solutions available on the portal soon.
Number Spelling • Read Simply Scheme, page 233, which has hints • Another hint (principle): don't force "everything" into the recursion.
Problem: find all the even numbers insentence of numbers (define (find-evens sent) (cond ((empty? sent) ;base case '() ) ((odd? (first sent)) ;rec case 1 (find-evens (bf sent)) ) (else ;rec case 2: even (se (first sent) (find-evens (bf sent))) ) )) (define (find-evens sent) (cond ( ;base case ) ( ;rec case 1: odd ) ( ;rec case 2: even ) ))
> (find-evens '(2 3 4 5 6)) sent = ( 2 3 4 5 6 ) (se 2 sent = ( 3 4 5 6 ) sent = ( 4 5 6 ) (se 4 sent = ( 5 6 ) sent = ( 6 ) (se 6 sent = ( ) () • (se 2 (se 4 (se 6 ()) • (2 4 6)
Why is recursion hard? • ONE function: • replicates itself, • knows how to stop, • knows how to combine the “replications” • There are many ways to think about recursion: you absolutely do not need to understand all of them. • Knowing recursion WILL help with all sorts of ways while programming, even if you don’t often use it.
Recursive patterns • Most recursive functions that operate on a sentence fall into: • Mapping: square-all • Counting: count-vowels, count-evens • Finding: member, first-even • Filtering: keep-evens • Testing: all-even? • Combining: sum-evens
What recursions aren’t covered by these patterns? • Weird ones like reverse, or downup • Ones that don’t traverse a single sentence • E.g., mad-libs takes a sentence of replacement words [e.g., ‘(fat Henry three)] and a sentence to mutate [e.g., ‘(I saw a * horse named * with * legs)] • Tree recursion: multiple recursive calls in a single recursive step
Advanced recursion Pascal’s Triangle • How many ways can you choose C things from R choices? • Coefficients of the (x+y)^R: look in row R • etc.
pair-all • Write pair-all, which takes a sentence of prefixes and a sentence of suffixes and returns a sentence pairing all prefixes to all suffixes. • (pair-all ‘(a b c) ‘(1 2 3)) (a1 b1 c1 a2 b2 c2 a3 b3 c3) • (pair-all ‘(spr s k) ‘(ite at ing ong)) (sprite sprat spring sprong site sat sing song kite kat king kong)