lec6 Recursion, Higher-Order Functions

lec6 Recursion, Higher-Order Functions - CSE 130 : Fall...

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

View Full Document Right Arrow Icon
1 CSE 130 : Fall 2006 Programming Languages Ranjit Jhala UC San Diego Lecture 6: Recursion, Higher-Order Functions We’ve covered a lot so far • Core ML features – Expressions, Values, Types • How to build complex values – Tuples, records, … • How to create, use complex types – Lists, trees, expressions,… – Pattern-matching Today: • More practice with recursion • Functions as values: taking, returning functions Example : Factorial let rec fac n = if n=0 then 1 else n * fac (n-1) ;; Base Expression Inductive Expression Induction Condition Example : Clone let rec clone x n = if n =0 then [] else x ::(clone x ( n -1)) ;; Base Expression Inductive Expression Induction Condition
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 Example : interval let rec interval i j = if i > j then [] else i ::(interval ( i +1) j ) ; Base Expression Inductive Expression Induction Condition Example : List Maximum let max x y = if x > y then x else y ; let listMax l = let rec helper cur l = if (null l ) then cur else helper (max cur (hd l ), tl l ) in helper (0, l ) ;; Find maximum element in +ve int list Base Expression Inductive Expression Induction Condition Example : List Maximum let max x y = if x > y then x else y let listMax l = let rec helper cur l = match l with [] -> cur | h :: t -> helper (max cur h ) t in helper (0, l ) ;; Find maximum element in +ve int list … in a more ML-ish way Base Expression Inductive Expression Base pattern Ind. pattern Example : List Append let rec append l1 l2 = match l1 with [] -> l2 | h :: t -> h :: (append t l2 )) ;; Roll our own @ Base Expression Inductive Expression Base “pattern” Ind. “pattern” Example : List Filter let rec filter f l = match l with [] -> [] | h :: t -> let t’ = filter f t in if ( f h ) then h :: t’ else t’ ;; Base Expression Base pattern Inductive Expression Ind. pattern
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 02/14/2008 for the course CSE 130 taught by Professor Jhala during the Fall '06 term at UCSD.

Page1 / 7

lec6 Recursion, Higher-Order Functions - CSE 130 : Fall...

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online