lecture-6

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

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

View Full Document Right Arrow Icon
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;;
Background image of page 1

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

View Full DocumentRight Arrow Icon
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
Background image of page 2
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!
Background image of page 3

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

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

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 Right Arrow Icon
Ask a homework question - tutors are online