CMSC 330: Organization of Programming Languages Object Oriented Programming with OCaml.

Slides:



Advertisements
Similar presentations
More ML Compiling Techniques David Walker. Today More data structures lists More functions More modules.
Advertisements

Modern Programming Languages, 2nd ed.
CMSC 330: Organization of Programming Languages Tuples, Types, Conditionals and Recursion or “How many different OCaml topics can we cover in a single.
Writing functions in OCaml. Defining a simple function # let add (x, y) = x + y;; val add : int * int -> int = Notice what this says: –add is a value.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
Control-Flow Graphs & Dataflow Analysis CS153: Compilers Greg Morrisett.
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Dan Grossman Winter 2013.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
Chapter ElevenModern Programming Languages1 A Fourth Look At ML.
Patterns in ML functions. Formal vs. actual parameters Here's a function definition (in C): –int add (int x, int y) { return x + y; } –x and y are the.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Introduction to ML – Part 1 Frances Spalding. Assignment 1 chive/fall05/cos441/assignments/a1.ht m
5/11/2015IT 3271 Types in ML (Ch 11) datatype bool = true | false; datatype 'element list = nil | :: of 'element * 'element list n Predefined, but not.
CSE341: Programming Languages Lecture 8 Lexical Scope and Function Closures Dan Grossman Fall 2011.
Road Map Introduction to object oriented programming. Classes
Chapter 3 Data Abstraction: The Walls. © 2005 Pearson Addison-Wesley. All rights reserved3-2 Abstract Data Types Modularity –Keeps the complexity of a.
Introduction to ML - Part 2 Kenny Zhu. What is next? ML has a rich set of structured values Tuples: (17, true, “stuff”) Records: {name = “george”, age.
Introduction to ML Last time: Basics: integers, Booleans, tuples,... simple functions introduction to data types This time, we continue writing an evaluator.
CS 201 Functions Debzani Deb.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
Chapter 9 Defining New Types. Objectives Explore the use of member functions when creating a struct. Introduce some of the concepts behind object-oriented.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
Chapter 6: User-Defined Functions
Patterns in OCaml functions. Formal vs. actual parameters Here's a function definition (in C): –int add (int x, int y) { return x + y; } –x and y are.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Built-in Data Structures in Python An Introduction.
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
A Second Look At ML 1. Outline Patterns Local variable definitions A sorting example 2.
A Third Look At ML Chapter NineModern Programming Languages, 2nd ed.1.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
CMSC 330: Organization of Programming Languages Functional Programming with OCaml.
CMSC 330: Organization of Programming Languages Maps and Folds Anonymous Functions.
CMSC 330: Organization of Programming Languages
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Chapter SevenModern Programming Languages1 A Second Look At ML.
CMSC 330: Organization of Programming Languages Operational Semantics.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
C++ Namespaces, Exceptions CSci 588: Data Structures, Algorithms and Software Design All material not from online sources copyright © Travis Desell, 2011.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
CSE 341 : Programming Languages Lecture 9 Lexical Scope, Closures Zach Tatlock Spring 2014.
1 Objective Caml (Ocaml) Aaron Bloomfield CS 415 Fall 2005.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
An introduction to functional programming using Haskell CENG242 –Recitation 1.
A Sample Program #include using namespace std; int main(void) { cout
Windows Programming Lecture 06. Data Types Classification Data types are classified in two categories that is, – those data types which stores decimal.
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
7/7/20161 Programming Languages and Compilers (CS 421) Dennis Griffith 0207 SC, UIUC Based in part on slides by Mattox.
Principles of programming languages 12: Functional programming
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Zach Tatlock Winter 2018.
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Dan Grossman Spring 2017.
Functions Inputs Output
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Dan Grossman Autumn 2018.
Objective caml Daniel Jackson MIT Lab for Computer Science 6898: Advanced Topics in Software Design March 18, 2002.
CMSC 202 Lesson 22 Templates I.
CSE 341 Section 5 Winter 2018.
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Dan Grossman Autumn 2017.
CSE-321 Programming Languages Introduction to Functional Programming
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Dan Grossman Spring 2016.
Templates I CMSC 202.
Variables in C Topics Naming Variables Declaring Variables
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Dan Grossman Spring 2019.
Presentation transcript:

CMSC 330: Organization of Programming Languages Object Oriented Programming with OCaml

CMSC 3302 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 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

CMSC 3303 Data Types Rect and Circle are type constructors- here a shape is either a Rect or a Circle Use pattern matching to deconstruct values, and do different things depending on constructor type shape = Rect of float * float (* width * length *)‏ | Circle of float (* radius *)‏ let area s = match s with Rect (wd, ln) -> wd *. ln | Circle rad -> rad *. rad * area (Rect (3.0, 4.0))‏ area (Circle 3.0)‏

CMSC 3304 Data Types, con't. type shape = Rect of float * float (* width * length *)‏ | Circle of float (* radius *)‏ let x = [Rect (3.0, 4.0) ; Circle 3.0; Rect (10.0, 22.5)] What's the type of x ? What's the type of x 's first element? x : shape list shape

CMSC 3305 Data Types (cont’d)‏ The arity of a constructor is the number of arguments it takes –A constructor with no arguments is nullary –Constructors must begin with uppercase letter type optional_int = None | Some of int let add_with_default a = function None -> a + 42 | Some n -> a + n add_with_default 3 None (* 45 *)‏ add_with_default 3 (Some 4) (* 7 *)‏ NOTES # type int_option = None | Some of int;; The OCaml compiler will warn of a function matching only Some … values and neglecting the None value: # let extract = function Some i -> i;; Warning: this pattern-matching is not exhaustive. Here is an example of a value that is not matched: None val extract : int_option -> int = This extract function then works as expected on Some … values: # extract (Some 3);; - : int = 3 but causes a Match_failure exception to be raised at run-time if a None value is given, as none of the patterns in the pattern match of the extract function match this value: # extract None;; Exception: Match_failure ("", 5, -40).

CMSC 3306 Polymorphic Data Types This option type can work with any kind of data –In fact, this option type is built-in to OCaml type 'a option = None | Some of 'a let add_with_default a = function None -> a + 42 | Some n -> a + n add_with_default 3 None (* 45 *)‏ add_with_default 3 (Some 4) (* 7 *)‏

CMSC 3307 Recursive Data Types We can build up lists this way: –Note: Don’t have nice [1; 2; 3] syntax for this kind of list type 'a list = Nil | Cons of 'a * 'a list let rec length l = function Nil -> 0 | Cons (_, t) -> 1 + (length t)‏ length (Cons (10, Cons (20, Cons (30, Nil))))‏

CMSC 3308 Exercise: A Binary Tree Data Type Write type bin_tree for ordered binary trees over int Implement the following empty : bin_tree is_empty : bin_tree -> bool contains : int -> bin_tree -> bool insert : int -> bin_tree -> bin_tree equals : bin_tree -> bin_tree -> bool map : (int -> int) -> bin_tree -> bin_tree fold : ('a -> int -> 'a) -> 'a -> bin_tree -> 'a What about remove?

CMSC 3309 Modules So far, most everything we’ve defined has been at the “top-level” of OCaml –This is not good software engineering practice A better idea: Use modules to group associated types, functions, and data together For lots of sample modules, see the OCaml standard library

CMSC Creating a Module module Shapes = struct type shape = Rect of float * float (* width * length *)‏ | Circle of float (* radius *)‏ let area = function Rect (w, l) -> w *. l | Circle r -> r *. r * let unit_circle = Circle 1.0 end;; unit_circle;; (* not defined *)‏ Shapes.unit_circle;; Shapes.area (Shapes.Rect (3.0, 4.0));; open Shapes;; (* import all names into current scope *)‏ unit_circle;; (* now defined *)‏

CMSC Modularity and Abstraction Another reason for creating a module is so we can hide details –For example, we can build a binary tree module, but we may not want to expose our exact representation of binary trees –This is also good software engineering practice

CMSC Module Signatures module type FOO = sig val add : int -> int -> int end;; module Foo : FOO = struct let add x y = x + y let mult x y = x * y end;; Foo.add 3 4;; (* OK *)‏ Entry in signature Supply function types Give type to module

CMSC Module Signatures (cont’d)‏ The convention is for signatures to be all capital letters –This isn't a strict requirement, though Items can be omitted from a module signature –This provides the ability to hide values The default signature for a module hides nothing

CMSC Abstract Types in Signatures Now definition of shape is hidden module type SHAPES = sig type shape val area : shape -> float val unit_circle : shape val make_circle : float -> shape val make_rect : float -> float -> shape end;; module Shapes : SHAPES = struct... let make_circle r = Circle r let make_rect x y = Rect (x, y)‏ end

CMSC Abstract Types in Signatures # Shapes.unit_circle - : Shapes.shape = (* OCaml won’t show impl *)‏ # Shapes.Circle 1.0 Unbound Constructor Shapes.Circle # Shapes.area (Shapes.make_circle 3.0)‏ - : float = # open Shapes;; # (* doesn’t make anything abstract accessible *)‏

CMSC Note for Project 4 You may wish to put the “nfa” type definition in the signature to get better debugging information from Ocaml REMOVE IT BEFORE YOU SUBMIT

CMSC ml and.mli files General structure: put the signature in a foo.mli file, the struct in a foo.ml file –Use the same names –Omit the sig...end and struct...end parts –The OCaml compiler will make a Foo module from these Similar to C file structure (.c/.h)‏ Not implemented in project 4 for simplicity

CMSC So Far, only Functional Programming We haven’t given you any way so far to change something in memory –All you can do is create new values from old This actually makes programming easier ! –You don’t care whether data is shared in memory Aliasing is irrelevant –Provides strong support for compositional reasoning and abstraction Ex: Calling a function f with argument x always produces the same result – and there are no side effects!

CMSC Imperative OCaml There are three basic operations on memory: –ref : 'a -> 'a ref Allocate an updatable reference –! : 'a ref -> 'a Read the value stored in reference –:= : 'a ref -> 'a -> unit Write to a reference let x = ref 3 (* x : int ref *)‏ let y = !x x := 4

CMSC Comparison to L- and R-values Recall that in C/C++/Java, there’s a strong distinction between l- and r-values A variable's meaning depends on where it appears in an assignment –On the right-hand side, it’s an r-value, and it refers to the contents of the variable –On the left-hand side, it’s an l-value, and it refers to the location the variable is stored in

CMSC L-Values and R-Values (cont’d) (in C)‏ Notice that x, y, and 3 all have type int int x, y; x = 3; y = x; 3 = x; Store 3 in location x Read contents of x and store in location y Makes no sense

CMSC Comparison to OCaml In OCaml, an updatable location and the contents of the location have different types –The location has a ref type int x, y; x = 3; y = x; 3 = x; let x = ref 0;; let y = ref 0;; x := 3;; (* x : int ref *)‏ y := (!x);; 3 := x;; (* 3 : int; error *)‏

CMSC Application: A ref in a Closure We can use refs to make things like counters that produce a fresh number “everywhere” let next = let count = ref 0 in function () -> let temp = !count in count := (!count) + 1; temp;; # next ();; - : int = 0 # next ();; - : int = 1 unit: this is how a function takes no argument

CMSC Semicolon Revisited; Side Effects Now that we can update memory, we have a real use for ; and () : unit –e1; e2 means evaluate e1, throw away the result, and then evaluate e2, and return the value of e2 –() means “no interesting result here” –It’s only interesting to throw away values or use () if computation does something besides return a result A side effect is a visible state change –Modifying memory –Printing to output –Writing to disk

CMSC The Trade-Off of Side Effects Side effects are absolutely necessary –That’s usually why we run software! We want something to happen that we can observe They also make reasoning harder –Order of evaluation now matters –Calling the same function in different places may produce different results –Aliasing is an issue If we call a function with refs r1 and r2, it might do strange things if r1 and r2 are aliased

CMSC Grouping with begin...end If you’re not sure about the scoping rules, use begin...end to group together statements with semicolons let x = ref 0 let f () = begin print_string "hello"; x := (!x) + 1 end

CMSC 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

CMSC Exceptions (cont’d)‏ Exceptions are declared with exception –They may appear in the signature as well Exceptions may take arguments –Just like type constructors –May also be nullary Catch exceptions with try...with... –Pattern-matching can be used in with –If an exception is uncaught, the current function exits immediately and control transfers up the call chain until the exception is caught, or until it reaches the top level

CMSC OCaml Functions Types & polymorphism Lists & tuples Pattern matching Recursion & inductive definitions Map and fold Currying Object-oriented style Modules Side effects Exceptions

CMSC OCaml Language Choices Implicit or explicit variable declarations? –Explicit – variables must be introduced with let before use –But you don’t need to specify types Static or dynamic types? –Static – but you don’t need to state types –OCaml does type inference to figure out types for you –Good: less work to write programs –Bad: easier to make mistakes, harder to find errors