100 likes | 247 Views
Scheme examples. Recursion. Iteration is achieved via recursion Selection is achieved via COND Review the following examples to learn to think recursively. Basic Strategy. Define the base case(s) as the termination points
E N D
Recursion • Iteration is achieved via recursion • Selection is achieved via COND • Review the following examples to learn to think recursively.
Basic Strategy • Define the base case(s) as the termination points • Use CAR and CDR to extract components from the list and then (if necessary) make recursive calls on the remainder of the list. • The “remainder of the list” should be getting smaller on each call to assure termination.
Iteration Summing elements in a list(table) int Addup (a,n) { sum=0; for (i=0, i<n; i++) sum+= a[i]; return sum; } int Addup (a,n) { sum=0; if (n==1) return a[0]; else return a[0]+Addup(a[1],n-1) } Recursively in c in lisp ( define ( Addup a ) ( cond ((NULL? a) 0) (ELSE (+ (car a) (Addup (cdr a)))) ) ) Note: if the list is nested, ( 1 ( 2 3 ) 4), this Addup will not work!
Iteration Summing elements in a list(table) Note: if the list is nested, ( 1 ( 2 3 ) 4), this Addup will not work! ( define ( Addup a ) ( cond ((NULL? a) 0) (ELSE (+ (car a) (Addup (cdr a)))) ) )
Iteration Summing elements in a list(table) ( define ( Addup a ) ( cond ((NULL? a) 0) (ELSE (+ (car a) (Addup (cdr a)))) ) ) ( Addup (3 6 2) ) a recursive call NULL? ( + 3 (Addup (6 2) ) ) initial call (3 6 2) false ( + 6 (Addup (2) ) ) next call (6 2) false ( + 2 (Addup ( ) ) ) next call (2) false next call ( ) true -> return 0 No recursive call
Iteration NOW RETURN RESULTS BACK ( Addup (3 6 2) ) 11 a recursive call NULL? ( + 3 8 ) ( + 3 (Addup (6 2) ) ) initial call (3 6 2) false 8 ( + 6 2 ) ( + 6 (Addup (2) ) ) next call (6 2) false 2 ( + 2 0 ) ( + 2 (Addup ( ) ) ) next call (2) false 0 next call ( ) true -> return 0 No recursive call
If test is true Tests (nested if) Recursive call (iteration) Simple member function (DEFINE (member atm lis) ( COND ( (NULL? lis) '() ) ( (EQ? atm (CAR lis)) #T) (ELSE (member atm (CDR lis) ) ) ) )
Equality of simple lists (DEFINE (equalsimp lis1 lis2) (COND ( (NULL? lis1) (NULL? lis2) ) ( (NULL? lis2) '() ) ( (EQ? (CAR lis1) (CAR lis2) ) (equalsimp (CDR lis1) (CDR lis2) ) ) (ELSE '() ) )) What happens with a list like ( a ( b c ) d ) ?
Equality of arbitrary list (DEFINE (equal lis1 lis2) (COND ( (NOT (LIST? lis1)) (EQ? lis1 lis2)) ( (NOT (LIST? lis2)) '() ) ( (NULL? lis1) (NULL? lis2)) ( (NULL? lis2) '()) ( (equal (CAR lis1) (CAR lis2) ) (equal (CDR lis1) (CDR lis2))) (ELSE '() ) )) Files can be found on the web site under PRACTICE link