lecture-6

# lecture-6 - Recap from last Week Three key ways to build...

This preview shows pages 1–4. Sign up to view the full content.

1 1 Recap from last Week Three key ways to build complex types/values 1. “Each-of” types Value of T contains value of T1 and a value of T2 2. “One-of” types Value of T contains value of T1 or a value of T2 3. “Recursive” Value of T contains (sub)-value of same type T 2 Today • More on recursion • Higher-order functions – taking and returning functions 3 Factorial let rec fact n = 4 Factorial let rec fact n = if n<=0 then 1 else n * fact (n-1) ;; 5 How does it execute? let rec fact n = if n<=0 then 1 else n * fact (n-1) ;; fac 3;; 6 How does it execute? let rec fact n = if n<=0 then 1 else n * fact (n-1) ;; fac 3;;

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
2 7 Tail recursion • Tail recursion: – recursion where all recursive calls are followed by a return – in other words: not allowed to do any between recursive call and return 8 Tail recursive factorial let fact x = 9 Tail recursive factorial let fact x = let rec helper x curr = if x <= 0 then curr else helper (x - 1) (x * curr) in helper x 1;; 10 How does it execute? let fact x = let rec helper x curr = if x <= 0 then curr else helper (x - 1) (x * curr) in helper x 1;; fact 3;; 11 How does it execute? let fact x = let rec helper x curr = if x <= 0 then curr else helper (x - 1) (x * curr) in helper x 1;; fact 3;; 12 Tail recursion • Tail recursion: – recursion where all recursive calls are followed by a return – in other words: not allowed to do any between recursive call and return • Why do we care about tail recursion? – it turns out that tail recursion can be optimized into a simple loop
3 13 Compiler can optimize! let fact x = let rec helper x curr = if x <= 0 then curr else helper (x - 1) (x * curr) in helper x 1;; fact(x) { curr := 1; while (1) { if (x <= 0) then { return curr } else { x := x – 1; curr := (x * curr) } } recursion! Loop!

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 01/08/2011 for the course CSE cse130 taught by Professor Cs during the Fall '10 term at UCSD.

### Page1 / 8

lecture-6 - Recap from last Week Three key ways to build...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online