Introduction to OCaml

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

CS 11 Ocaml track: lecture 2

CSCI-GA Scripting Languages

Programming Languages

Introduction to OCaml

Plan (next 4 weeks) 1. Fast forward. 2. Rewind. 3. Slow motion. Rapid introduction to what s in OCaml. Go over the pieces individually

Programming Languages and Compilers (CS 421)

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming

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

Programming Languages

Programming Languages

OCaml. History, Variants. ML s holy trinity. Interacting with ML. Base type: Integers. Base type: Strings. *Notes from Sorin Lerner at UCSD*

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

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

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

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

CS Lecture 6: Map and Fold. Prof. Clarkson Spring Today s music: Selections from the soundtrack to 2001: A Space Odyssey

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

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

CS 321 Programming Languages

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

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

CS Lecture 6: Map and Fold. Prof. Clarkson Fall Today s music: Selections from the soundtrack to 2001: A Space Odyssey

Lecture: Functional Programming

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

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming

Datatype declarations

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming

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

Programming Languages

Begin at the beginning

Introduction to Objective Caml

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

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

SML A F unctional Functional Language Language Lecture 19

Case by Case. Chapter 3

Lists. Michael P. Fourman. February 2, 2010

Any questions. Say hello to OCaml. Say hello to OCaml. Why readability matters. History, Variants. Plan (next 4 weeks)

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

# true;; - : bool = true. # false;; - : bool = false 9/10/ // = {s (5, "hi", 3.2), c 4, a 1, b 5} 9/10/2017 4

Metaprogramming assignment 3

CSc 372 Comparative Programming Languages

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

Type Checking and Type Inference

Some Advanced ML Features

Lecture #23: Conversion and Type Inference

CSc 372. Comparative Programming Languages. 8 : Haskell Function Examples. Department of Computer Science University of Arizona

Programming Languages and Compilers (CS 421)

Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = "Hello";

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

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

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

L3 Programming September 19, OCaml Cheatsheet

CMSC 330, Fall 2013, Practice Problems 3

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

CS558 Programming Languages

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

The Substitution Model

Types, Type Inference and Unification

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

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

Programming Languages and Techniques (CIS120)

Chapter 3 Linear Structures: Lists

Currying fun f x y = expression;

CSE 341 Section 5. Winter 2018

INF121: Functional Algorithmic and Programming

CS 11 Ocaml track: lecture 4. Today: modules

ITT8060: Advanced Programming (in F#)

A quick introduction to SML

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

So what does studying PL buy me?

The Substitution Model. Nate Foster Spring 2018

FUNCTIONAL PROGRAMMING

Functional Programming. Introduction To Cool

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

CSCC24 Functional Programming Typing, Scope, Exceptions ML

Programming Languages and Techniques (CIS120)

Cunning Plan. One-Slide Summary. Functional Programming. Functional Programming. Introduction to COOL #1. Classroom Object-Oriented Language

Chapter 3 Linear Structures: Lists

CSC324 Principles of Programming Languages

Booleans (aka Truth Values) Programming Languages and Compilers (CS 421) Booleans and Short-Circuit Evaluation. Tuples as Values.

CSE 307: Principles of Programming Languages

COSE212: Programming Languages. Lecture 4 Recursive and Higher-Order Programming

Lists. Adrian Groza. Department of Computer Science Technical University of Cluj-Napoca

CMSC 330, Fall 2013, Practice Problem 3 Solutions

Algebraic data types. The case against null

CSE 307: Principles of Programming Languages

Which of the following expressions has the type int list?

Functional Paradigm II

Inductive Data Types

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

Homework 8: Matrices Due: 11:59 PM, Oct 30, 2018

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

Homework 3 COSE212, Fall 2018

Exercises on ML. Programming Languages. Chanseok Oh

CMSC 330: Organization of Programming Languages

CSE 3302 Programming Languages Lecture 8: Functional Programming

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

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

CIS 120 Midterm I October 2, Name (printed): Username (login id):

Transcription:

Introduction to OCaml Jed Liu Department of Computer Science Cornell University CS 6110 Lecture 26 January 2009 Based on CS 3110 course notes and an SML tutorial by Mike George Jed Liu Introduction to OCaml 1

Installing OCaml Linux: yum install ocaml apt-get install ocaml emerge dev-lang/ocaml Windows: http://caml.inria.fr/ocaml/release.en.html Get the Microsoft-based native Win32 port OCaml toplevel system demo Jed Liu Introduction to OCaml 1

Declaring Variables let sixeleven = 611 (* A local variable declaration *) let fortytwo = let six = 6 and nine = 7 in six * nine Jed Liu Introduction to OCaml 2

Base Types let x : int = -7 let y : char = a let z : string = "moo" let w : float = 3.14159 let v : bool = true OCaml has type inference Type declarations are optional in many places But having them makes it much easier to debug type errors! Jed Liu Introduction to OCaml 3

Tuples and Datatypes (* Tuples (a.k.a. product types) *) let t1 : int * int = (3, 5) let t2 : string * bool * char = ("moo", true, q ) let t3 : unit = () (* The empty tuple *) (* A simple datatype (like enum or union) *) type suit = Spades Diamonds Hearts Clubs let c : suit = Clubs Jed Liu Introduction to OCaml 4

More Datatypes (* Datatype constructors can carry values *) (* and be recursive (and look like CFGs) *) type var = string type exp = Var of var Lam of var * exp App of exp * exp let id : exp = Lam ("x", Var "x") let w : exp = App (Lam ("x", App (Var "x", Var "x")), Lam ("x", App (Var "x", Var "x"))) Can build up tuples and datatypes... How to break them down and actually use them? Jed Liu Introduction to OCaml 5

Pattern Matching let t1 : int * int =... (* Binds two variables at once *) let (a, b) = t1 (* Use _ for "don t care" *) let (_, b) = t1 (* Can match constants too *) let (a, 5) = t1 OCaml warns about non-exhaustive patterns Jed Liu Introduction to OCaml 6

More Pattern Matching let suitname : string = match c with Spades -> "spades" Diamonds -> "diamonds" Hearts -> "hearts" Clubs -> "clubs" (* Base types are just special datatypes *) (* and can also be pattern-matched *) let b : bool =... let x : int = match b with true -> 1 false -> 0 Jed Liu Introduction to OCaml 7

More Pattern Matching let suitname : string = match c with Spades -> "spades" Diamonds -> "diamonds" Hearts -> "hearts" Clubs -> "clubs" (* Base types are just special datatypes *) (* and can also be pattern-matched *) let b : bool =... let x : int = match b with true -> 1 false -> 0 (* Says the same thing and is better style: *) let x : int = if b then 1 else 0 Jed Liu Introduction to OCaml 7

A Warning about Pattern Matching (* What does this evaluate to? *) let pair = (42, 611) let x = 611 match pair with (x, 611) -> 0 (42, x) -> 1 _ -> 2 Jed Liu Introduction to OCaml 8

A Warning about Pattern Matching (* What does this evaluate to? *) let pair = (42, 611) let x = 611 match pair with (x, 611) -> 0 (42, x) -> 1 _ -> 2 Patterns can refer to datatype constructors and constants But cannot refer to pre-existing variables They can only declare new variables Jed Liu Introduction to OCaml 8

Functions (* A variable with a function value *) let square : int -> int = fun (x:int) -> x * x (* anonymous fun! *) (* Same thing, more succinct *) let square (x:int) : int = x * x Jed Liu Introduction to OCaml 9

Recursive Functions let rec fact (x:int) : int = if x = 0 then 1 else x * (fact (x-1)) (* Mutually recursive functions *) let rec isodd (x:int) : bool = x!= 0 && iseven (x-1) and iseven (x:int) : bool = x = 0 isodd (x-1) Jed Liu Introduction to OCaml 10

More Functions (* How many arguments does this take? *) let rec gcd (a, b) : int = if b = 0 then a else gcd (b, a mod b) Jed Liu Introduction to OCaml 11

More Functions (* How many arguments does this take? *) let rec gcd (a, b) : int = if b = 0 then a else gcd (b, a mod b) (* More explicitly: *) let rec gcd (p : int * int) : int = match p with (a, b) -> if b = 0 then a else gcd (b, a mod b) Jed Liu Introduction to OCaml 11

Curried Functions let rec gcd (a, b) : int = if b = 0 then a else gcd (b, a mod b) (* Preferred style: *) let rec gcd (a:int) (b:int) : int = if b = 0 then a else gcd b (a mod b) (* Has type int -> int -> int *) (* More explicitly: *) let rec gcd (a:int) : int -> int = fun (b:int) -> if b = 0 then a else gcd b (a mod b) Jed Liu Introduction to OCaml 12

A Minor Tangent... We have gcd : int * int -> int gcd : int -> (int -> int) Through currying and uncurrying, these types are somehow equivalent Squint hard and you might see logical propositions... A B = C A = (B = C)...which are logically equivalent! Jed Liu Introduction to OCaml 13

Local Declarations (including local functions) (* Newton s method of approximation *) let rec newton f guess : float = let goodenough = abs float (f guess) < 0.0001 in if goodenough then guess else let f x = (f x -. f (x -. 0.0001)) /. 0.0001 in let newguess = guess -. (f guess) /. (f guess) in newton f newguess Jed Liu Introduction to OCaml 14

Polymorphism (* What is this function s type? *) let id x = x Jed Liu Introduction to OCaml 15

Polymorphism (* What is this function s type? *) let id x = x (* More explicitly *) let id (x : a) : a = x (* A polymorphic datatype *) type a lst = Empty Cons of ( a * a lst) let rec map (f: a -> b) (l: a lst) : b lst = match l with Empty -> Empty Cons (hd, tl) -> Cons (f hd, map f tl) Jed Liu Introduction to OCaml 15

Lists OCaml has lists built-in [] is the empty list :: is the cons operator @ is the append operator [1; 2; 3] is a three-element list (note the semicolons) let rec reverse (l : a list) : a list = match l with [] -> [] hd :: tl -> (reverse tl) @ [hd] A fancy list pattern: [a; (42, [611]); (b, c::d)] Jed Liu Introduction to OCaml 16

Putting It All Together Demo: #use "fv.ml" Jed Liu Introduction to OCaml 17

Summary Types, tuples, datatypes Pattern matching Higher-order functions, anonymous functions, currying Polymorphism Jed Liu Introduction to OCaml 18

Resources CS 3110 notes http://www.cs.cornell.edu/courses/cs3110/2008fa/ Objective CAML Tutorial http://www.ocaml-tutorial.org/ SML vs. OCaml http://www.mpi-sws.org/ rossberg/sml-vs-ocaml.html OCaml manual http://caml.inria.fr/pub/docs/manual-ocaml/ Jed Liu Introduction to OCaml 19