lec4-2x2

# lec4-2x2 - CSE 130: Fall 2011 Programming Languages Ranjit...

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

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

View Full Document

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.

Unformatted text preview: CSE 130: Fall 2011 Programming Languages Ranjit Jhala UC San Diego Lecture 4: Variables and Scope News • PA 1 due tomorrow at 5pm • Lets first wrap up with data types... What about “Recursive” types ? type int_list = Nil | Cons of int * int_list Think about this! What are values of int_list ? Nil Cons(3,Nil) Cons(2,Cons(3,Nil)) Cons(1,Cons(2,Cons(3,Nil))) Nil Cons 3, Cons 2, Cons 1, Lists aren’t built-in ! Lists are a derived type: built using elegant core datatype int_list = Nil | Cons of int * int_list Lists are a derived type: built using elegant core! 1. Each-of 2. One-of 3. Recursive :: is just a pretty way to say “Cons” is just a pretty way to say “Nil” Some functions on Lists : Length let rec len l = match l with Nil-> | Cons(h,t) -> 1 + (len t) Base Expression Inductive Expression Base pattern Ind pattern let rec len l = match l with Nil-> | Cons(_,t) -> 1 + (len t) let rec len l = match l with Cons(_,t) -> 1 + (len t) | _-> Matches everything, no binding Pattern-matching in order- Must match with Nil Code Mirrors Data 6 6 Some functions on Lists : listMax let rec listMax xs = match xs with Base Expression Base pattern Nil-> | Cons(h,t) -> max h (listMax t) Inductive Expression Ind pattern Code Mirrors Data 8 6 Some functions on Lists : Append let rec append (l1,l2) = Base Expression Inductive Expression Base pattern Ind pattern • Find the right induction strategy – Base case: pattern + expression – Induction case: pattern + expression Well designed datatype gives strategy Code Mirrors Data 10 6 null, hd, tl are all functions … Bad ML style: More than aesthetics ! Pattern-matching better than test-extract: • ML checks all cases covered • ML checks no redundant cases • …at compile-time: – fewer errors (crashes) during execution – get the bugs out ASAP! Another Example: Calculator We want an arithmetic calculator to evaluate expressions like: • 4.0 + 2.9 • 3.78 – 5.92 • (4.0 + 2.9) * (3.78 5.92 = 6.9 = -2.14 = 14.766 • (4.0 + 2.9) * (3.78 -5.92) Q: Whats a ML datatype for such expressions ?...
View Full Document

## This note was uploaded on 12/11/2011 for the course CSE 130 taught by Professor Jhala during the Fall '06 term at UCSD.

### Page1 / 10

lec4-2x2 - CSE 130: Fall 2011 Programming Languages Ranjit...

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

View Full Document
Ask a homework question - tutors are online