Introduction to OCaml

Similar documents
Functions. Nate Foster Spring 2018

CSCI-GA Scripting Languages

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

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

FUNCTIONAL PROGRAMMING

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

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

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

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

CSE 341: Programming Languages

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

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

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

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

Data Types. Guest Lecture: Andrew Myers Spring 2018

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

Data Types. Prof. Clarkson Fall Today s music: Pokémon Theme by Jason Paige

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

Introduction to ML. Based on materials by Vitaly Shmatikov. General-purpose, non-c-like, non-oo language. Related languages: Haskell, Ocaml, F#,

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

Introduction to Nate Foster Spring 2018

Introduction to Prof. Clarkson Fall Today s music: Prelude from Final Fantasy VII by Nobuo Uematsu (remastered by Sean Schafianski)

Introduction to SML Getting Started

CSE 341: Programming Languages

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

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

The Substitution Model

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

CMSC 330, Fall 2013, Practice Problems 3

Introduction to Prof. Clarkson Fall Today s music: Prelude from Final Fantasy VII by Nobuo Uematsu (remastered by Sean Schafianski)

Introduction to Prof. Clarkson Fall Today s music: Prelude from Final Fantasy VII by Nobuo Uematsu (remastered by Sean Schafianski)

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

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

Introduction to Prof. Clarkson Fall Today s music: Prelude from Final Fantasy VII by Nobuo Uematsu (remastered by Sean Schafianski)

Functional Programming

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

Chapter 11 :: Functional Languages

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

Types, Type Inference and Unification

The Substitution Model. Nate Foster Spring 2018

CS 11 Ocaml track: lecture 2

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

L3 Programming September 19, OCaml Cheatsheet

CSE 130 [Winter 2014] Programming Languages

Hard deadline: 3/28/15 1:00pm. Using software development tools like source control. Understanding the environment model and type inference.

Introduction to Objective Caml

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

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

CMSC 330, Fall 2013, Practice Problem 3 Solutions

CSE 341 Section 5. Winter 2018

Introduction to OCaml

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

CS 11 Haskell track: lecture 1

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

Functional Languages. CSE 307 Principles of Programming Languages Stony Brook University

Scope and Introduction to Functional Languages. Review and Finish Scoping. Announcements. Assignment 3 due Thu at 11:55pm. Website has SML resources

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

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

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

SNU Programming Language Theory

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

LECTURE 16. Functional Programming

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

CMSC 330: Organization of Programming Languages. Rust Basics

CS558 Programming Languages

List Functions, and Higher-Order Functions

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

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

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

Functional Programming. Big Picture. Design of Programming Languages

Type Inference Systems. Type Judgments. Deriving a Type Judgment. Deriving a Judgment. Hypothetical Type Judgments CS412/CS413

CMSC 330: Organization of Programming Languages

CSE 130 [Winter 2014] Programming Languages

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

Programming Languages Lecture 14: Sum, Product, Recursive Types

Programming Language Pragmatics

Functional Programming

Back to OCaml. Summary of polymorphism. Example 1. Type inference. Example 2. Example 2. Subtype. Polymorphic types allow us to reuse code.

Lists. Michael P. Fourman. February 2, 2010

Behavioral Equivalence

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

CS558 Programming Languages

The design of a programming language for provably correct programs: success and failure

Recap: Functions as first-class values

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

Safe Smart Contract Programming with Scilla

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

4/19/2018. Chapter 11 :: Functional Languages

INF121: Functional Algorithmic and Programming

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

CIS24 Project #3. Student Name: Chun Chung Cheung Course Section: SA Date: 4/28/2003 Professor: Kopec. Subject: Functional Programming Language (ML)

CMSC 330: Organization of Programming Languages

1. true / false By a compiler we mean a program that translates to code that will run natively on some machine.

Datatype declarations

Concepts of Programming Languages

02157 Functional Programming. Michael R. Ha. Lecture 2: Functions, Types and Lists. Michael R. Hansen

Monday Feb 16, 5pm. solve these equalities. Midterm Thursday Feb 12. covers only ocaml part of the course, assignments 1 through 3.

CS3110 Spring 2016 Lecture 6: Modules

Tracing Ambiguity in GADT Type Inference

Transcription:

Fall 2018 Introduction to OCaml Yu Zhang Course web site: http://staff.ustc.edu.cn/~yuzhang/tpl

References Learn X in Y Minutes Ocaml Real World OCaml Cornell CS 3110 Spring 2018 Data Structures and Functional Programming Introduction Functions Lists Data types More Variants Higher-order programming Official website http://ocaml.org/ A web-based interpreter: http://try.ocamlpro.com/

What is a functional language? A functional language: defines computations as mathematical functions avoids mutable state State: the information maintained by a computation Mutable: can be changed (antonym: immutable) Functional Imperative Abstraction level Higher Lower Develop robust SW Easier Harder State Immutable Mutable Expression What to compute How to compute

Why study functional programming? Functional languages predict the future Garbage collection Java [1995], LISP [1958] Generics Java 5 [2004], ML [1990] Higher-order functions C#3.0 [2007], Java 8 [2014], LISP [1958] Type inference C++11 [2011], Java 7 [2011] and 8, ML [1990] What s next?

Why study functional programming? Functional languages are sometimes used in industry

Why study functional programming? Functional languages are elegant Elegant code is easier to read and maintain Elegant code might (not) be easier to write

ML programming language Statically typed, general-purpose programming language Meta-Language of the LCF theorem proving system LCF: Logic for Computable Functions Type safe, with formal semantics Compiled language, but intended for interactive use Combination of Lisp and Algol-like features Expression-oriented Higher-order functions Garbage collection Abstract data types Module system Exceptions Robin Milner, ACM Turing-Award for ML, LCF Theorem Prover,

OCaml (Objective Caml) http://ocaml.org/

OCaml Immutable programming Variable s values cannot destructively be changed; makes reasoning about program easier! Algebraic datatypes and pattern matching Makes definition and manipulation of complex data structures easy to express First-class functions Functions can be passed around like ordinary values Static type-checking Reduce number of run-time errors Automatic type inference No burden to write down types of every single variable Parametric polymorphism Enables construction of abstractions that work across many data types Garbage collection Automated memory management eliminates many run-time errors Modules Advanced system for structuring large systems

Expressions (terms) Expressions: Primary building block of OCaml programs akin to statements or commands in imperative languages can get arbitrarily large since any expression can contain subexpressions, etc. Every kind of expression has: Syntax Semantics: Type-checking rules (static semantics): produce a type or fail with an error message Evaluation rules (dynamic semantics): produce a value (or exception or infinite loop) Used only on expressions that type-check

Values A value is an expression that does not need any further evaluation 34 is a value of type int 34+17 is an expression of type int but is not a value

if expressions Syntax if e1 then e2 else e3 Evaluation if e1 evaluates to true, and if e2 evaluates to v, then if e1 then e2 else e3 evaluates to v if e1 evaluates to false, and if e3 evaluates to v, then if e1 then e2 else e3 evaluates to v Type checking if e1: bool and e2:t and e3:t then if e1 then e2 else e3 : t

Question To what value does this expression evaluate? if 22=0 then 1 else 2 if 22=0 then "bear" else 2

Question To what value does this expression evaluate? if 22=0 then 1 else 2 2 if 22=0 then "bear" else 2

Question To what value does this expression evaluate? if 22=0 then 1 else 2 2 if 22=0 then "bear" else 2 Does not type check!!! So never gets a chance to be evaluated.

Function definitions Examples rec is required because the body includes a recursive function call let rec pow (x : int) (y : int) : int = if y=0 then 1 else x * pow x (y-1) let rec pow x y = if y=0 then 1 else x * pow x (y-1) let cube x = pow x 3 let cube (x : int) : int = pow x 3 no types written down! compiler does type inference

Function definitions Syntax let rec f x1 x2... xn = e note: rec can be omitted if function is not recursive Evaluation Not an expression! Just defining the function; will be evaluated later, when applied Function Types Type t -> u is the type of a function that takes input of type t and returns output of type u Type t1 -> t2 -> u is the type of a function that takes input of type t1 and another input of type t2 and returns output of type u

Function definitions Syntax let rec f x1 x2... xn = e note: rec can be omitted if function is not recursive Evaluation Not an expression! Just defining the function; will be evaluated later, when applied Type-checking Conclude that f : t1 ->... -> tn -> u if e:u under these assumptions: x1:t1,..., xn:tn (arguments with their types) f: t1 ->... -> tn -> u (for recursion)

Function application Syntax f e1 e2... en Evaluation 1. Evaluate arguments e1...en to values v1...vn 2. Find the definition of f: let f x1... xn = e 3. Substitute vi for xi in e yielding new expression e 4. Evaluate e to a value v, which is result Type-checking if f : t1 ->... -> tn -> u and e1:t1,..., en:tn then f e1... En:u

Anonymous functions Examples fun x -> x+1 is an anonymous function and we can bind it to a name: let inc = fun x -> x+1 Note dual purpose for -> syntax: function types, function values fun is a keyword :)

Anonymous functions Syntax fun x1 x2... xn -> e Evaluation A function is a value Type-checking (fun x1... xn -> e) : t1->...->tn->t if e:t under assumptions x1:t1,..., xn:tn

Lists let lst = [1;2;3] let empty = [] let longer = 5::lst let another = 5::1::2::3::[] let rec sum xs = match xs with [] -> 0 h::t -> h + sum t let six = sum lst let zero = sum empty

Lists let lst = [1;2;3] let empty = [] let longer = 5::lst let another = 5::1::2::3::[] [1;2;3]: int list []: t list for any type t If e1 : t and e2 : t list then e1::e2 : t list let rec sum xs = match xs with [] -> 0 h::t -> h + sum t let six = sum lst let zero = sum empty

Variants vs. records vs. tuples Variants: one-of types aka sum types type t = C1... Cn Records, tuples: each-of types aka product types type t = {f1:t1;...; fn:tn} {f1=p1;...; fn=pn} e.f (e1,e2,...,en)

Lists are just variants OCaml effectively codes up lists as variants type 'a list = [ ] :: of 'a * 'a list list is a type constructor parameterized on type variable 'a [ ] and :: are constructors Just a bit of syntactic magic in the compiler to use [ ] and :: instead of alphabetic identifiers

Options are just variants OCaml effectively codes up options as variants type 'a option = None Some of 'a option is a type constructor parameterized on type variable 'a None and Some are constructors

Exceptions are (mostly) just variants OCaml effectively codes up exceptions as slightly strange variants type exn exception MyNewException of string Type exn is an extensible variant that may have new constructors added after its original definition Raise exceptions with raise e, where e is a value of type exn Handle exceptions with pattern matching, just like you would process any variant

Higher-order functions let double x = 2*x let square x = x*x let quad x = double (double x) let fourth x = square (square x) let twice f x = f (f x) val twice : ('a -> 'a) -> 'a -> 'a let quad x = twice double x let fourth x = twice square x

Currying Currying: A function with multiple parameters is sugar for a function with a tuple parameter Curried form: high-order function let plus (x, y) = x + y is sugar for let plus (z : int * int) = match z with (x, y) -> x + y let plus = fun (z : int * int) -> match z with (x, y) -> x + curried form let plus x y = x + y

Currying Currying: A function with multiple parameters is sugar for a function with a tuple parameter Curried form: high-order function let plus (x, y) = x + y is sugar for let plus (z : int * int) = match z with (x, y) -> x + y let plus = fun (z : int * int) -> match z with (x, y) -> x + y curried form let plus x y = x + y plus: int * int -> int plus: int -> int -> int

Map and reduce Fold has many synonyms/cousins in various functional languages, including scan and reduce Google organizes large-scale data-parallel computations with MapReduce [OSDI 2004 Jeff Dean et al.] [Google s MapReduce] abstraction is inspired by the map and reduce primitives present in Lisp and many other functional languages. We realized that most of our computations involved applying a map operation to each logical record in our input in order to compute a set of intermediate key/value pairs, and then applying a reduce operation to all the values that shared the same key in order to combine the derived data appropriately." [Dean and Ghemawat, 2008]

Map let rec add1 = function [ ] -> [ ] h::t -> (h+1)::(add1 t) let rec concat3110 = function [ ] -> [ ] h::t -> (h^"3110")::(concat3110 t) let rec map f = function [ ] -> [] x::xs -> (f x)::(map f xs) map : ('a -> 'b) -> 'a list -> 'b list

Map let rec add1 = function [ ] -> [ ] h::t -> (h+1)::(add1 t) let add1 = List.map (fun x -> x+1) let rec concat3110 = function [ ] -> [ ] h::t -> (h^"3110")::(concat3110 t) let rec map f = function [ ] -> [] x::xs -> (f x)::(map f xs) map : ('a -> 'b) -> 'a list -> 'b list let concat3110 = List.map (fun s -> s^"3110")

Filter let rec filter f = function [] -> [] x::xs -> if f x then x::(filter f xs) else filter f xs filter : ('a -> bool) -> 'a list -> 'a list