CSE341: Programming Languages Lecture 4 Records, Datatypes, Case Expressions. Dan Grossman Spring 2013

Similar documents
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists. Dan Grossman Fall 2011

CSE 341: Programming Languages

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013

CS Lecture 5: Pattern Matching. Prof. Clarkson Fall Today s music: Puff, the Magic Dragon by Peter, Paul & Mary

CSE 341: Programming Languages

Racket. CSE341: Programming Languages Lecture 14 Introduction to Racket. Getting started. Racket vs. Scheme. Example.

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists. Zach Tatlock Winter 2018

Function definitions. CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists. Example, extended. Some gotchas. Zach Tatlock Winter 2018

CSE341, Fall 2011, Midterm Examination October 31, 2011

Preparing for Class: Watch le Videos! What is an ML program?

Programming Languages Dan Grossman Welcome to the Class!

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Fall 2011

CSE341: Programming Languages Lecture 7 First-Class Functions. Dan Grossman Winter 2013

CS152: Programming Languages. Lecture 11 STLC Extensions and Related Topics. Dan Grossman Spring 2011

CSE 341: Programming Languages

News. Programming Languages. Recap. Recap: Environments. Functions. of functions: Closures. CSE 130 : Fall Lecture 5: Functions and Datatypes

Lists. Prof. Clarkson Fall Today s music: "Blank Space" by Taylor Swift

CSE 341 Section 5. Winter 2018

Recap from last time. Programming Languages. CSE 130 : Fall Lecture 3: Data Types. Put it together: a filter function

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures

CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion. Zach Tatlock Winter 2018

Begin at the beginning

CSE 341 : Programming Languages

CSE341: Programming Languages Lecture 11 Type Inference. Dan Grossman Spring 2016

CMSC 330: Organization of Programming Languages. OCaml Expressions and Functions

Recap. Recap. If-then-else expressions. If-then-else expressions. If-then-else expressions. If-then-else expressions

Part I: Written Problems

CSE341, Fall 2011, Midterm Examination October 31, 2011

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

Programming Languages

Introduction to OCaml

Part I: Written Problems

Review. CS152: Programming Languages. Lecture 11 STLC Extensions and Related Topics. Let bindings (CBV) Adding Stuff. Booleans and Conditionals

Side note: Tail Recursion. Begin at the beginning. Side note: Tail Recursion. Base Types. Base Type: int. Base Type: int

CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Dan Grossman Winter 2013

Tail Recursion: Factorial. Begin at the beginning. How does it execute? Tail recursion. Tail recursive factorial. Tail recursive factorial

Programming Languages

CSCI-GA Scripting Languages

CSE341, Spring 2013, Final Examination June 13, 2013

CSE341 Section 3. Standard-Library Docs, First-Class Functions, & More

Datatype declarations

Programming Languages

Data Types. Guest Lecture: Andrew Myers Spring 2018

CSE341: Programming Languages Lecture 22 OOP vs. Functional Decomposition; Adding Operators & Variants; Double-Dispatch. Dan Grossman Autumn 2018

Ruby logistics. CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Ruby: Not our focus. Ruby: Our focus. A note on the homework

CSC324- TUTORIAL 5. Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides

CSE 341, Spring 2011, Final Examination 9 June Please do not turn the page until everyone is ready.

Programming Languages

CSci 4223 Principles of Programming Languages

COMP 105 Homework: Type Systems

Programming Languages and Compilers (CS 421)

CSE341: Programming Languages Lecture 17 Implementing Languages Including Closures. Dan Grossman Autumn 2018

CSE341 Autumn 2017, Midterm Examination October 30, 2017

CSE 341, Autumn 2015, Ruby Introduction Summary

CSE341 Spring 2016, Final Examination June 6, 2016

CSE341 Spring 2017, Final Examination June 8, 2017

CSE341: Programming Languages Lecture 25 Subtyping for OOP; Comparing/Combining Generics and Subtyping. Dan Grossman Winter 2013

Recap: ML s Holy Trinity. Story So Far... CSE 130 Programming Languages. Datatypes. A function is a value! Next: functions, but remember.

Dialects of ML. CMSC 330: Organization of Programming Languages. Dialects of ML (cont.) Features of ML. Functional Languages. Features of ML (cont.

CSE 130 Programming Languages. Datatypes. Ranjit Jhala UC San Diego

What is it? CMSC 433 Programming Language Technologies and Paradigms Spring Approach 1. Disadvantage of Approach 1

CSci 4223 Lecture 12 March 4, 2013 Topics: Lexical scope, dynamic scope, closures

CSE 130 Programming Languages. Lecture 3: Datatypes. Ranjit Jhala UC San Diego

Functions. Nate Foster Spring 2018

Lecture 3: Recursion; Structural Induction

Types and Programming Languages. Lecture 5. Extensions of simple types

CSE 341, Autumn 2005, Assignment 3 ML - MiniML Interpreter

The type checker will complain that the two branches have different types, one is string and the other is int

News. Programming Languages. Complex types: Lists. Recap: ML s Holy Trinity. CSE 130: Spring 2012

Recap: ML s Holy Trinity

Programming Languages

Object-Oriented Programming (OOP) Basics. CSCI 161 Introduction to Programming I

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

Announcements. CSCI 334: Principles of Programming Languages. Lecture 5: Fundamentals III & ML

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

CSE341 Spring 2017, Final Examination June 8, 2017

The story so far. Elements of Programming Languages. Pairs in various languages. Pairs

Programming Languages

To figure this out we need a more precise understanding of how ML works

Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming

Exercises on ML. Programming Languages. Chanseok Oh

CSE 341: Programming Languages

A Third Look At ML. Chapter Nine Modern Programming Languages, 2nd ed. 1

Mutable Data Types. Prof. Clarkson Fall A New Despair Mutability Strikes Back Return of Imperative Programming

CS 360: Programming Languages Lecture 12: More Haskell

CS-XXX: Graduate Programming Languages. Lecture 23 Types for OOP; Static Overloading and Multimethods. Dan Grossman 2012

G Programming Languages Spring 2010 Lecture 4. Robert Grimm, New York University

Programming Languages

CSE 374: Programming Concepts and Tools. Eric Mullen Spring 2017 Lecture 4: More Shell Scripts

CS152: Programming Languages. Lecture 23 Advanced Concepts in Object-Oriented Programming. Dan Grossman Spring 2011

CS558 Programming Languages

CSE 303: Concepts and Tools for Software Development

CSE341: Programming Languages Lecture 26 Course Victory Lap. Dan Grossman Spring 2016

CSE 505: Concepts of Programming Languages

Some Advanced ML Features

Chapter 3 Linear Structures: Lists

Programming Language Concepts, cs2104 Lecture 04 ( )

Transcription:

CSE341: Programming Languages Lecture 4 Records, Datatypes, Case Expressions Dan Grossman Spring 2013

Five different things 1. Syntax: How do you write language constructs? 2. Semantics: What do programs mean? (Evaluation rules) 3. Idioms: What are typical patterns for using language features to express your computation? 4. Libraries: What facilities does the language (or a well-known project) provide standard? (E.g., file access, data structures) 5. Tools: What do language implementations provide to make your job easier? (E.g., REPL, debugger, code formatter, ) Not actually part of the language These are 5 separate issues In practice, all are essential for good programmers Many people confuse them, but shouldn t 2

Our Focus This course focuses on semantics and idioms Syntax is usually uninteresting A fact to learn, like The American Civil War ended in 1865 People obsess over subjective preferences Libraries and tools crucial, but often learn new ones on the job We are learning semantics and how to use that knowledge to understand all software and employ appropriate idioms By avoiding most libraries/tools, our languages may look silly but so would any language used this way 3

How to build bigger types Already know: Have various base types like int bool unit char Ways to build (nested) compound types: tuples, lists, options Today: more ways to build compound types First: 3 most important type building blocks in any language Each of : A t value contains values of each of t1 t2 tn One of : A t value contains values of one of t1 t2 tn Self reference : A t value can refer to other t values Remarkable: A lot of data can be described with just these building blocks Note: These are not the common names for these concepts 4

Examples Tuples build each-of types int * bool contains an int and a bool Options build one-of types int option contains an int or it contains no data Lists use all three building blocks int list contains an int and another int list or it contains no data And of course we can nest compound types ((int * int) option) * (int list list)) option 5

Rest of this Lecture Another way to build each-of types in ML Records: have named fields Connection to tuples and idea of syntactic sugar A way to build and use our own one-of types in ML For example, a type that contains an int or a string Will lead to pattern-matching, one of ML s coolest and strangest-to-java-programmers features Later in course: How OOP does one-of types Key contrast with procedural and functional programming 6

Records Record values have fields (any name) holding values {f1 = v1,, fn = vn} Record types have fields (and name) holding types The order of fields in a record value or type never matters REPL alphabetizes fields just for consistency Building records: {f1 : t1,, fn : tn} {f1 = e1,, fn = en} Accessing components: #myfieldname e (Evaluation rules and type-checking as expected) 7

Example Evaluates to {name = "Amelia", id = 41123-12} {id = 41111, name = "Amelia"} And has type {id : int, name : string} If some expression such as a variable x has this type, then get fields with: #id x #name x Note we did not have to declare any record types The same program could also make a {id=true,ego=false} of type {id:bool,ego:bool} 8

By name vs. by position Little difference between (4,7,9) and {f=4,g=7,h=9} Tuples a little shorter Records a little easier to remember what is where Generally a matter of taste, but for many (6? 8? 12?) fields, a record is usually a better choice A common decision for a construct s syntax is whether to refer to things by position (as in tuples) or by some (field) name (as with records) A common hybrid is like with Java method arguments (and ML functions as used so far): Caller uses position Callee uses variables Could totally do it differently; some languages have 9

The truth about tuples Previous lecture gave tuples syntax, type-checking rules, and evaluation rules But we could have done this instead: Tuple syntax is just a different way to write certain records (e1,,en) is another way of writing {1=e1,,n=en} t1* *tn is another way of writing {1:t1,,n:tn} In other words, records with field names 1, 2, In fact, this is how ML actually defines tuples Other than special syntax in programs and printing, they don t exist You really can write {1=4,2=7,3=9}, but it s bad style 10

Syntactic sugar Tuples are just syntactic sugar for records with fields named 1, 2, n Syntactic: Can describe the semantics entirely by the corresponding record syntax Sugar: They make the language sweeter Will see many more examples of syntactic sugar They simplify understanding the language They simplify implementing the language Why? Because there are fewer semantics to worry about even though we have the syntactic convenience of tuples Another example we saw: andalso and orelse vs. if then else 11

Datatype bindings A strange (?) and totally awesome (!) way to make one-of types: A datatype binding datatype mytype = TwoInts of int * int Str of string Pizza Adds a new type mytype to the environment Adds constructors to the environment: TwoInts, Str, and Pizza A constructor is (among other things), a function that makes values of the new type (or is a value of the new type): TwoInts : int * int -> mytype Str : string -> mytype Pizza : mytype 12

The values we make datatype mytype = TwoInts of int * int Str of string Pizza Any value of type mytype is made from one of the constructors The value contains: A tag for which constructor (e.g., TwoInts) The corresponding data (e.g., (7,9)) Examples: TwoInts(3+4,5+4) evaluates to TwoInts(7,9) Str(if true then hi else bye ) evaluates to Str( hi ) Pizza is a value 13

Using them So we know how to build datatype values; need to access them There are two aspects to accessing a datatype value 1. Check what variant it is (what constructor made it) 2. Extract the data (if that variant has any) Notice how our other one-of types used functions for this: null and issome check variants hd, tl, and valof extract data (raise exception on wrong variant) ML could have done the same for datatype bindings For example, functions like isstr and getstrdata Instead it did something better 14

Case ML combines the two aspects of accessing a one-of value with a case expression and pattern-matching Pattern-matching much more general/powerful (lecture 5) Example: fun f x = (* f has type mytype -> int *) case x of Pizza => 3 TwoInts(i1,i2) => i1+i2 Str s => String.size s A multi-branch conditional to pick branch based on variant Extracts data and binds to variables local to that branch Type-checking: all branches must have same type Evaluation: evaluate between case of and the right branch 15

Patterns In general the syntax is: case e0 of p1 => e1 p2 => e2 pn => en For today, each pattern is a constructor name followed by the right number of variables (i.e., C or C x or C(x,y) or ) Syntactically most patterns (all today) look like expressions But patterns are not expressions We do not evaluate them We see if the result of e0 matches them 16

Why this way is better 0. You can use pattern-matching to write your own testing and data-extractions functions if you must But do not do that on your homework 1. You cannot forget a case (inexhaustive pattern-match warning) 2. You cannot duplicate a case (a type-checking error) 3. You will not forget to test the variant correctly and get an exception (like hd []) 4. Pattern-matching can be generalized and made more powerful, leading to elegant and concise code 17