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

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

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

Some Advanced ML Features

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

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

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

Functional Programming. Big Picture. Design of Programming Languages

So what does studying PL buy me?

LECTURE 16. Functional Programming

COP4020 Programming Assignment 1 - Spring 2011

CSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGraw-Hill Companies, Inc.

Types, Type Inference and Unification

Overloading, Type Classes, and Algebraic Datatypes

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

CS 11 Haskell track: lecture 1

Programming Languages and Compilers (CS 421)

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

Data Types The ML Type System

CSCI-GA Scripting Languages

Example Scheme Function: equal

It is better to have 100 functions operate one one data structure, than 10 functions on 10 data structures. A. Perlis

Introduction to Haskell

CPS 506 Comparative Programming Languages. Programming Language Paradigm

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

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

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

CSE 3302 Programming Languages Lecture 8: Functional Programming

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

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

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

Software System Design and Implementation

Scheme Tutorial. Introduction. The Structure of Scheme Programs. Syntax

Programming Languages and Compilers (CS 421)

Recursion. Tjark Weber. Functional Programming 1. Based on notes by Sven-Olof Nyström. Tjark Weber (UU) Recursion 1 / 37

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

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

Chapter 15. Functional Programming Languages

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

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

Introduction to Haskell

Introduction to OCaml

Haskell An Introduction

CSC324 Principles of Programming Languages

According to Larry Wall (designer of PERL): a language by geniuses! for geniuses. Lecture 7: Haskell. Haskell 98. Haskell (cont) - Type-safe!

Introduction to Haskell

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

CSCI 2041: Introduction

Functional Programming

Imperative languages

Programming Languages

Lecture 12: Data Types (and Some Leftover ML)

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

FUNCTIONAL PROGRAMMING

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

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

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

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

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

Principles of Programming Languages

Chapter 15. Functional Programming Languages

An introduction to functional programming. July 23, 2010

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

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

CS3110 Spring 2016 Lecture 6: Modules

Note that pcall can be implemented using futures. That is, instead of. we can use

Programming Languages. So why study PL? A Programming Language. A different language is a different vision of life. CSE 130 : Fall 2015

Programming Languages. So why study PL? A Programming Language. A different language is a different vision of life. CSE 130 : Spring 2015

Recursion. Lars-Henrik Eriksson. Functional Programming 1. Based on a presentation by Tjark Weber and notes by Sven-Olof Nyström

Types and Type Inference

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

CS558 Programming Languages

Programming Languages

Begin at the beginning

Metaprogramming assignment 3

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

A Fourth Look At ML. Chapter Eleven Modern Programming Languages, 2nd ed. 1

Programming in Haskell Aug-Nov 2015

CS558 Programming Languages

Functional Programming and Haskell

Functional Programming

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

Programming Language Concepts: Lecture 19

Introduction to Functional Programming and Haskell. Aden Seaman

Lists. Michael P. Fourman. February 2, 2010

Programming Languages

A Programming Language. A different language g is a different vision of life. CSE 130 : Fall Two variables. L1: x++; y--; (y=0)?

Redefinition of an identifier is OK, but this is redefinition not assignment; Thus

Types and Type Inference

Concepts of Programming Languages

Programming Languages

Sometimes it s good to be lazy

Functional Programming for Imperative Programmers

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

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

A Brief Introduction to Standard ML

CS 11 Ocaml track: lecture 2

Symbolic Computation and Common Lisp

Transcription:

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

The ML Programming Language General purpose programming language designed by Robin Milner in 1970 Meta Language for verification Impure Functional Programming Language Eager call by value evaluation Static strongly typed (like Java unlike C) Protect its abstraction via type checking and runtime checking Polymorphic Type Inference Dialects: OCaml, Standard ML, F#

C is not Type Safe int j; union { int i, int * p } x; x.i = 17 ; j = *(x.p); int i, *p; i =17 p = (int *) i;

Factorial in ML let rec fac n = if n = 0 then 1 else n * fac (n - 1) let rec fac n : int = if n = 0 then 1 else n * fac (n - 1) let rec fac = function 0 -> 1 n -> n * fac(n - 1) // val fac : int -> int = <fun> let fac n = let rec ifac n acc = if n=0 then acc else ifac n-1, n * acc in ifac n, 1

Why Study ML? Functional programming will make you think differently about programming Mainstream languages are all about state Functional programming is all about values ML is cutting edge Polymorphic Type inference References Module system Practical (small) Programming Language New ideas can help make you a better programmer, in any language

Plan Basic Programming in ML Type Inference for ML ML Modules & References

Simple Types Booleans true -: bool = true false -: bool = false if then else types must match Integers 0, 1, 2, -: int =0, 1, +, *, -: int * int -> int Strings I am a string -: string = I am a string Floats 1.0, 2., 3.14159, :- float = 1, 2, 3.14159

Scope Rules ML enforces static nesting on identifiers To be explained lets let x = e1 in e2 ( x.e2) e1

Tuples 4, 5, abc :- (int*int*string)=(4, 5, abc ) let max1 (r1, r2) : float = if r1 < r2 then r2 else r1 val max1: float * float -> float = fun let args = (3.5, 4.5) val args: float * float = (3.5, 4.5) max1 args :- float = 4.5 let y(x 1 : t 1, x 2 : t2,, x n : t n )= e

Pattern-Matching Tuples let x 1 : t 1, x 2 : t 2,, x n :t n = e let max1 (pair : float * float) : float = let (r1, r2) = pair in if r1 < r2 then r2 else r1 val max1: float * float -> float = fun let minmax (a, b) : float * float = if a < b then (a, b) else (b, a) val minmax: float * float -> float *float= fun let (mn, mx) = minmax (2.0, 1.0) val mn float 1 val mx float 2 The compiler guarantees the absence of runtime errors

User-Defined Types type day = Sun Mon Tue Wed Thu Fri Sat let int_to_day (i : int) : day = match i mod 7 with 0 -> Sun 1 -> Mon 2 -> Tue 3 -> Wed 4 -> Thu 5 -> Fri _ -> Sat

Records type person = {first:string; last:string; age:int} {first= John ; last= Amstrong ; age=77} :- person ={first= John; last= Amstrong ; age=77} {first= John ; last= Amstrong ; age=77}.age :- int = 77 let ja = {first= John ; last= Amstrong ; age=77} val ja : person = {first= John ; last= Amstrong ; age=77} let = {first=first; last=last} = ja val first:string= John val last:string = Amstrong

Variant Records Provides a way to declare Algebraic data types type expression = Number of int Plus of expression * expression let rec eval_exp (e : expression) : int = match e with Number(n) -> n Plus (left, right) -> eval_exp(left) + eval_exp(right) val eval_exp : expression -> int = <fun> eval_exp (Plus(Plus(Number(2), Number(3)), Number(5))) :- int = 10

Variant Records in C struct exp { int tag ; /* Select between cases */ union { struct number { int : number; } struct plus { struct exp *left, *right; } } }

Scope Local nested scopes Let constructs introduce a scope let f x = e1 in e2 let x = 2 and y = 3 in x + y let rec even x = x = 0 odd (x-1) and odd x = not (x = 0 not (even (x-1))) in odd 3110

Polymorphism A Polymorphic expression may have many types There is a most general type The compiler infers types automatically Programmers can restrict the types Pros: Code reuse Guarantee consistency Cons: Compile-time Some limits on programming let max1 (r1, r2) = if r1 < r2 then r2 else r1 val max1: a * a -> a = fun max1 (5, 7) : - int = 7 max1 (5, 7.5)

Polymorphic Lists [ ] - : 'a list = [] [2; 7; 8 ] - : int list = [2; 7; 8] 2 :: (7 :: (8 ::[ ])) - : int list = [2; 7; 8] [(2, 7) ; (4, 9) ; 5] Error: This expression has type int but an expression was expected of type int * int

Functions on Lists let rec length l = match l with [] -> 0 hd :: tl -> 1 + length tl val length : 'a list -> int = <fun> length [1; 2; 3] + length [ red ; yellow ; green ] :- int = 6 length [ red ; yellow ; 3]

Higher Order Functions Functions are first class objects Passed as parameters Returned as results Practical examples Google map/reduce

Map Function on Lists Apply function to every element of list let rec map f arg = function [] -> [] hd :: tl -> f hd :: (map f tl) val map : ('a -> 'b) -> 'a list -> 'b list = <fun> map (fun x -> x+1) [1;2;3] [2,3,4] Compare to Lisp (define map (lambda (f xs) (if (eq? xs ()) () (cons (f (car xs)) (map f (cdr xs))) )))

More Functions on Lists Append lists Reverse a list let rec append l1 l2 = match l1 with [] -> l2 hd :: tl -> hd :: append (tl l2) let rec reverse l = function [] -> [] hd :: tl -> append (reverse tl) [hd] Questions How efficient is reverse? Can it be done with only one pass through list?

More Efficient Reverse let rev list = let rec aux acc = function [] -> acc h::t -> aux (h::acc) t in aux [] list val rev : 'a list -> 'a list = <fun> 1 3 2 2 2 2 3 3 1 3 1 1

Currying let plus (x, y) = x + y val plus : int * int -> int = fun 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 let plus x y = x + y val plus : int -> int -> int let p1 = plus 5 val p1 : int -> int = fun let p2 = p1 7 val p2 : int = 12

Functional Programming Languages PL types evaluation Side-effect scheme Weakly typed Eager yes ML OCAML F# Haskell Polymorphic strongly typed Polymorphic strongly typed Eager Lazy References None

Things to Notice Pure functions are easy to test prop_revrev l = reverse(reverse l) == l In an imperative or OO language, you have to set up the state of the object and the external state it reads or writes make the call inspect the state of the object and the external state perhaps copy part of the object or global state, so that you can use it in the post condition

Things to Notice Types are everywhere. reverse:: [w] -> [w] Usual static-typing panegyric omitted... In ML, types express high-level design, in the same way that UML diagrams do, with the advantage that the type signatures are machine-checked Types are (almost always) optional: type inference fills them in if you leave them out

Recommended ML Textbooks L. C. PAULSON: ML for the Working Programmer J. Ullman: Elements of ML Programming R. Harper: Programming in Standard ML

Recommended Ocaml Textbooks Xavier Leroy: The OCaml system release 4.02 Part I: Introduction Jason Hickey: Introduction to Objective Caml Yaron Minsky, Anil Madhavapeddy, Jason Hickey: Real World Ocaml

Summary Functional programs provide concise coding Compiled code compares with C code Successfully used in some commercial applications F#, ERLANG, Jane Street Ideas used in imperative programs Good conceptual tool Less popular than imperative programs