CMSC 330: Organization of Programming Languages

Similar documents
CMSC 330: Organization of Programming Languages. OCaml Data Types

OCaml Data CMSC 330: Organization of Programming Languages. User Defined Types. Variation: Shapes in Java

CS 11 Ocaml track: lecture 2

CS Lectures 2-3. Introduction to OCaml. Polyvios Pratikakis

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

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

CMSC 330: Organization of Programming Languages

CMSC 430 Introduction to Compilers. Fall Everything (else) you always wanted to know about OCaml (but were afraid to ask)

COMP 150-AVS Fall OCaml and Functional Programming

CMSC 330, Fall 2013, Practice Problems 3

Topic 7: Algebraic Data Types

Why OCaml? Introduction to Objective Caml. Features of OCaml. Applications written in OCaml. Stefan Wehr

Introduction to Objective Caml

CMSC 631. Functional Programming with OCaml

Tuples. CMSC 330: Organization of Programming Languages. Examples With Tuples. Another Example

CSC324 Principles of Programming Languages

CMSC 330, Fall 2013, Practice Problem 3 Solutions

Mini-ML. CS 502 Lecture 2 8/28/08

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

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

Inductive Data Types

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

CMSC 330: Organization of Programming Languages. Lets, Tuples, Records

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

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

CS 360: Programming Languages Lecture 10: Introduction to Haskell

Note first midterm date: Wed. evening, Feb. 23 Today's class: Types in OCaml and abstract syntax

CSCI-GA Scripting Languages

Some Advanced ML Features

Parametric types. map: ( a (a b) a list b list. filter: ( a bool) a list a list. Why? a and b are type variables!

CMSC 330: Organization of Programming Languages. OCaml Higher Order Functions

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

Background. CMSC 330: Organization of Programming Languages. Useful Information on OCaml language. Dialects of ML. ML (Meta Language) Standard ML

Introduction to OCaml

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

Algebraic Types. Chapter 14 of Thompson

CS 457/557: Functional Languages

CMSC 330: Organization of Programming Languages. OCaml Higher Order Functions

CMSC 330: Organization of Programming Languages. OCaml Higher Order Functions

Sum-of-Product Data Types

Exercises on ML. Programming Languages. Chanseok Oh

Sum-of-Product Data Types

Algebraic data types. The case against null

Standard ML. Data types. ML Datatypes.1

n n Try tutorial on front page to get started! n spring13/ n Stack Overflow!

CIS 120 Midterm II November 8, Name (printed): Pennkey (login id):

An introduction introduction to functional functional programming programming using usin Haskell

CMSC 330: Organization of Programming Languages

Lecture: Functional Programming

Informatics 1 Functional Programming Lecture 9. Algebraic Data Types. Don Sannella University of Edinburgh

CS 360: Programming Languages Lecture 12: More Haskell

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

CSE 130 [Winter 2014] Programming Languages

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

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples

Parametric types. aka: what s up with those a???

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

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

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

CMSC 330: Organization of Programming Languages

Haskell 98 in short! CPSC 449 Principles of Programming Languages

Lexical and Syntax Analysis. Abstract Syntax

CSE 3302 Programming Languages Lecture 8: Functional Programming

Programming Languages

CSCE 314 Programming Languages

Recap: ML s Holy Trinity

Lecture 19: Functions, Types and Data Structures in Haskell

CS 320: Concepts of Programming Languages

CSC/MAT-220: Lab 6. Due: 11/26/2018

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Software System Design and Implementation

CMSC 330: Organization of Programming Languages. Objects and Functional Programming

CS558 Programming Languages

Types, Semantics, and Programming Languages (IK3620)

Programming Languages

Topics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited

OCaml. ML Flow. Complex types: Lists. Complex types: Lists. The PL for the discerning hacker. All elements must have same type.

CMSC330 Fall 2016 Midterm #1 2:00pm/3:30pm

Overloading, Type Classes, and Algebraic Datatypes

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

Programming Languages and Techniques (CIS120)

CIS 120 Midterm II November 8, 2013 SOLUTIONS

CMSC 330: Organization of Programming Languages. Basic OCaml Modules

Harvard School of Engineering and Applied Sciences CS 152: Programming Languages

CSCI 2041: Functions, Mutation, and Arrays

Programming Languages and Techniques (CIS120)

CIS 120 Midterm II November 7, Name (printed): Pennkey (login id):

User-Defined Algebraic Data Types

From last time. News. Example. Example. Typechecking let. Typechecking let. Pick up your first two quizzes after class. Assignment #2 due tomorrow

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Introduction to OCaml

This example highlights the difference between imperative and functional programming. The imperative programming solution is based on an accumulator

CMSC330 Fall 2014 Midterm 2 Solutions

Programming Languages. Next: Building datatypes. Suppose I wanted. Next: Building datatypes 10/4/2017. Review so far. Datatypes.

Pascal: operations on basic data structures (selection) (I) 2.3 Accessing and manipulating data

A Second Look At ML. Chapter Seven Modern Programming Languages, 2nd ed. 1

Programming Languages. Datatypes

Fundamental of Programming (C)

CSE 130: Programming Languages. Polymorphism. Ranjit Jhala UC San Diego

CSC Java Programming, Fall Java Data Types and Control Constructs

Transcription:

CMSC 330: Organization of Programming Languages CMSC330 Fall 2017 OCaml Data Types CMSC330 Fall 2017 1

OCaml Data So far, we ve seen the following kinds of data Basic types (int, float, char, string) Lists Ø One kind of data structure Ø A list is either [ ] or h::t, deconstructed with pattern matching Tuples and Records Ø Let you collect data together in fixed-size pieces Functions How can we build other data structures? Building everything from lists and tuples is awkward 2

User Defined Types type can be used to create new names for types Useful for combinations of lists and tuples Examples type my_type = int * (int list) let (x:my_type) = (3, [1; 2]) type my_type2 = int*char*(int*float) let (y:my_type2) = (3, a, (5, 3.0)) 3

(User-Defined) Variants type coin = Heads Tails let flip x = match x with Heads -> Tails Tails -> Heads let rec count_heads x = Combined list match x with and variant [] -> 0 patterns possible (Heads::x ) -> 1 + count_heads x (_::x ) -> count_heads x In simplest form: Like a C enum Basic pattern matching resembles C switch 4

Constructing and Destructing Variants Syntax type t = C1 Cn the Ci are called constructors Ø Must begin with a capital letter Evaluation A constructor Ci is already a value Destructing a value v of type t is done by pattern matching on v ; the patterns are the constructors Ci Type Checking Ci : t (for each Ci in t s definition) 5

Data Types: Variants with Data We can define variants that carry data too Not just a constructor, but a constructor plus values type shape = Rect of float * float (* width*length *) Circle of float (* radius *) Rect and Circle are constructors where a shape is either a Rect(w,l) Ø for any floats w and l or a Circle r Ø for any float r 6

Data Types (cont.) let area s = match s with Rect (w, l) -> w *. l Circle r -> r *. r *. 3.14 ;; area (Rect (3.0, 4.0));; (* 12.0 *) area (Circle 3.0);; (* 9.42 *) Use pattern matching to deconstruct values Can bind pattern values to data parts Data types are aka algebraic data types are aka tagged unions 7

Data Types (cont.) type shape = Rect of float * float (* width*length *) Circle of float (* radius *) let lst = [Rect (3.0, 4.0) ; Circle 3.0] What's the type of lst? shape list What's the type of lst's first element? shape 8

Variation: Shapes in Java Compare this to OCaml public interface Shape { public double area(); } class Rect implements Shape { private double width, length; Rect (double w, double l) { this.width = w; this.length = l; } class Circle implements Shape { private double rad; Circle (double r) { this.rad = r; } } double area() { return width * length; } } double area() { return rad * rad * 3.14159; } 9

Option Type type optional_int = None Some of int let divide x y = if y!= 0 then Some (x/y) else None let string_of_opt o = match o with Some i -> string_of_int i None -> nothing let p = divide 1 0;; print_string (string_of_opt p);; (* prints nothing *) let q = divide 1 1;; print_string (string_of_opt q);; (* prints 1 *) Comparing to Java: None is like null, while Some i is like an Integer(i) object 10

Polymorphic Option Type A Polymorphic version of option type can work with any kind of data As int option, char option, etc... type a option = Some of a None In fact, this option type is built into OCaml Polymorphic parameter: like Option<T> in Java let opthd l = match l with [] -> None x::_ -> Some x let p = opthd [];; (* p = None *) let q = opthd [1;2];; (* q = Some 1 *) let r = opthd [ a ];; (* r = Some a *) 11

Recursive Data Types We can build up lists with recursive variant types type 'a mylist = Nil Cons of 'a * 'a mylist let rec len = function Nil -> 0 Cons (_, t) -> 1 + (len t) len (Cons (10, Cons (20, Cons (30, Nil)))) (* evaluates to 3 *) Won t have nice [1; 2; 3] syntax for this kind of list 12

Constructing and Destructing Variants Syntax type t = C1 [of t1] Cn [of tn] the Ci are called constructors Ø Must begin with a capital letter; may include associated data notated with brackets [] to indicate it s optional Evaluation A constructor Ci is a value if it has no assoc. data Ø Ci vi is a value if it does Destructing a value of type t is by pattern matching Ø patterns are constructors Ci with data components, if any Type Checking Ci [vi] : t [if vi has type ti] 13

Data Type Representations Values in a data type are stored 1. Directly as integers 2. As pointers to blocks in the heap The image part with relationship ID rid3 was not found in the file. type t = A of int B C of int * int D 14

Exercise: A Binary Tree Data Type Write type bin_tree for binary trees over int Trees should be ordered (binary search tree) Implement the following empty : bin_tree is_empty : bin_tree -> bool member : int -> bin_tree -> bool insert : int -> bin_tree -> bin_tree remove: int -> bin_tree -> bin_tree equal : bin_tree -> bin_tree -> bool fold : (int -> 'a -> 'a) -> bin_tree -> 'a -> 'a 15

Quiz 1 type foo = (int * (string list)) list Which one of the following could match foo? A. [(3, foo, bar )] B. [(5, [ foo, bar ])] C. [(7, [ foo ; bar ])] D. [(9, [( foo, bar )])] 16

Quiz 1 type foo = (int * (string list)) list Which one of the following could match foo? A. [(3, foo, bar )] B. [(5, [ foo, bar ])] C. [(7, [ foo ; bar ])] D. [(9, [( foo, bar )])] 17

Quiz 2: What does this evaluate to? type num = Int of int Float of float;; let plus a b = match a, b with Int i, Int j -> Int (i+j) Float i, Float j -> Float (i +. j) Float i, Int j -> Float (i +. float_of_int j) ;; plus (Float 3.0) (Int 2);; A. float = 5. B. num = Int 5 C. Type Error D. num = Float 5. 18

Quiz 2: What does this evaluate to? type num = Int of int Float of float;; let plus a b = match a, b with Int i, Int j -> Int (i+j) Float i, Float j -> Float (i +. j) Float i, Int j -> Float (i +. float_of_int j) ;; plus (Float 3.0) (Int 2);; A. float = 5. B. num = Int 5 C. Type Error D. num = Float 5. 19

Quiz 3: What does this evaluate to? A. float = 45.3 B. Error C. float = 42.0 D. No output let foo f = match f with None -> 42.0 Some n -> n +. 42.0 ;; foo 3.3;; 20

Quiz 3: What does this evaluate to? A. float = 45.3 B. Error C. float = 42.0 D. No output let foo f = match f with None -> 42.0 Some n -> n +. 42.0 ;; foo 3.3;; foo (Some 3.3) 21

OCaml Exceptions exception My_exception of int let f n = if n > 0 then raise (My_exception n) else raise (Failure "foo") let bar n = try f n with My_exception n -> Printf.printf "Caught %d\n" n Failure s -> Printf.printf "Caught %s\n" s 22

Exceptions (cont.) Exceptions are declared with exception They may appear in the signature as well Exceptions may take arguments Just like type constructors May also have no arguments Catch exceptions with try...with... Pattern-matching can be used in with If an exception is uncaught Ø Current function exits immediately Ø Control transfers up the call chain Ø Until the exception is caught, or until it reaches the top level 23

OCaml Exceptions (cont.) Exceptions may be thrown by I/O statements Common way to detect end of file Need to decide how to handle exception Example try (input_char stdin) (* reads 1 char *) with End_of_file -> 0 (* return 0? *) try read_line () (* reads 1 line *) with End_of_file -> (* return? *) 24

OCaml Exceptions (cont.) failwith:raise exception Failure with the given string. invalid_arg:raise exception Invalid_argument with the given string Not_found:Raised if the object does not exist let div x y = if y = 0 failwith "divide by zero else x/y;; let lst =[(1,"alice");(2,"bob");(3,"cat")];; let lookup key lst = try List.assoc key lst with Not_found -> "key does not exist" 25