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.

Slides:



Advertisements
Similar presentations
Functional Programming Lecture 10 - type checking.
Advertisements

CS3012: Formal Languages and Compilers Static Analysis the last of the analysis phases of compilation type checking - is an operator applied to an incompatible.
More ML Compiling Techniques David Walker. Today More data structures lists More functions More modules.
Modern Programming Languages, 2nd ed.
ML Lists.1 Standard ML Lists. ML Lists.2 Lists  A list is a finite sequence of elements. [3,5,9] ["a", "list" ] []  Elements may appear more than once.
A Third Look At ML 1. Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order.
Detecting Bugs Using Assertions Ben Scribner. Defining the Problem  Bugs exist  Unexpected errors happen Hardware failures Loss of data Data may exist.
ML Exceptions.1 Standard ML Exceptions. ML Exceptions.2 Exceptions – The Need  An extensive part of the code is error handling  A function can return.
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists Dan Grossman Winter 2013.
F28PL1 Programming Languages Lecture 14: Standard ML 4.
CMSC 330: Organization of Programming Languages Tuples, Types, Conditionals and Recursion or “How many different OCaml topics can we cover in a single.
ML Lists.1 Standard ML Lists. ML Lists.2 Lists  A list is a finite sequence of elements. [3,5,9] ["a", "list" ] []  ML lists are immutable.  Elements.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
Programming Languages Section 1 1 Programming Languages Section 1. SML Fundamentals Xiaojuan Cai Spring 2015.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
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.
CS 320: Compiling Techniques David Walker. People David Walker (Professor) 412 Computer Science Building office hours: after each.
Introduction to ML – Part 1 Frances Spalding. Assignment 1 chive/fall05/cos441/assignments/a1.ht m
ML Exceptions.1 Standard ML Exceptions. ML Exceptions.2 Exceptions – The Need  An extensive part of the code is error handling  A function can return.
Introduction to ML – Part 1 Kenny Zhu. Assignment 2 chive/fall07/cos441/assignments/a2.ht m
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
CS 320: Compiling Techniques David Walker. People David Walker (Professor) 412 Computer Science Building office hours: after each.
Introduction to ML Last time: Basics: integers, Booleans, tuples,... simple functions introduction to data types This time, we continue writing an evaluator.
Introduction to ML You will be responsible for learning ML on your own. Today I will cover some basics Read Robert Harper’s notes on “an introduction to.
Fixing Broken Programs. How do you figure out what’s wrong? Look carefully at the error message. Locate the error – Most messages have line numbers –
CS 320: Compiling Techniques David Walker. People David Walker (Professor) 412 Computer Science Building office hours: after each.
CS 320: Compiling Techniques David Walker. People David Walker (Professor) 412 Computer Science Building office hours: after each.
OCaml The PL for the discerning hacker.. Hello. I’m Zach, one of Sorin’s students.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
CSE-321 Programming Languages Introduction to Functional Programming (Part II) POSTECH March 13, 2006 박성우.
Programming Language Concepts (CIS 635) Elsa L Gunter 4303 GITC NJIT,
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.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Chapter 9: Functional Programming in a Typed Language.
A Second Look At ML 1. Outline Patterns Local variable definitions A sorting example 2.
F28PL1 Programming Languages Lecture 13: Standard ML 3.
A Third Look At ML Chapter NineModern Programming Languages, 2nd ed.1.
0 Odds and Ends in Haskell: Folding, I/O, and Functors Adapted from material by Miran Lipovaca.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
CMSC 330: Organization of Programming Languages Operational Semantics a.k.a. “WTF is Project 4, Part 3?”
Chapter SevenModern Programming Languages1 A Second Look At ML.
CSED101 INTRODUCTION TO COMPUTING SUM TYPE 유환조 Hwanjo Yu.
CMSC 330: Organization of Programming Languages Operational Semantics.
LECTURE 3 Compiler Phases. COMPILER PHASES Compilation of a program proceeds through a fixed series of phases.  Each phase uses an (intermediate) form.
More Data Types CSCE 314 Spring CSCE 314 – Programming Studio Defining New Data Types Three ways to define types: 1.type – Define a synonym for.
1 Objective Caml (Ocaml) Aaron Bloomfield CS 415 Fall 2005.
A Sample Program #include using namespace std; int main(void) { cout
CSE-321 Programming Languages Introduction to Functional Programming POSTECH March 8, 2006 박성우.
Principles of programming languages 12: Functional programming
Programming Languages
ML: a quasi-functional language with strong typing
Programming Languages Dan Grossman 2013
ML Again ( Chapter 7) Patterns Local variable definitions
Programming Languages
Objective caml Daniel Jackson MIT Lab for Computer Science 6898: Advanced Topics in Software Design March 18, 2002.
Context.
FP Foundations, Scheme In Text: Chapter 14.
Functions, Patterns and Datatypes
CSE 341 Section 5 Winter 2018.
Functions, Patterns and Datatypes
CSE-321 Programming Languages Introduction to Functional Programming
Declarative Computation Model Single assignment store (VRH 2
Functions, Patterns and Datatypes
CSE-321 Programming Languages Introduction to Functional Programming
Fundamental Programming
Data Types Every variable has a given data type. The most common data types are: String - Text made up of numbers, letters and characters. Integer - Whole.
Functions, Patterns and Datatypes
Programming Languages Dan Grossman 2013
Presentation transcript:

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 = 35} Lists: 3::4::5::nil or Datatypes Functions And more! We put things together in a more complex program

An interpreter Interpreters are usually implemented as a series of transformers: stream of characters abstract syntax lexing/ parsing evaluate abstract value print stream of characters

A little language (LL) An arithmetic expression e is a boolean value an if statement (if e1 then e2 else e3) an integer an add operation a test for zero (isZero e)

LL abstract syntax in ML datatype term = Bool of bool | If of term * term * term | Num of int | Add of term * term | IsZero of term -- constructors are capitalized -- constructors can take a single argument of a particular type type of a tuple another eg: string * char vertical bar separates alternatives

LL abstract syntax in ML Add (Num 2, Num 3) represents the expression “2 + 3” Add Num 23

LL abstract syntax in ML If (Bool true, Num 0, Add (Num 2, Num 3)) represents “if true then 0 else 2 + 3” Add Num 2 3 true BoolNum 0 If

Function declarations fun isValue t = case t of Num n => true | Bool b => true | _ => false function name function parameter default pattern matches anything

What is the type of the parameter t? Of the function? fun isValue t = case t of Num n => true | Bool b => true | _ => false function name function parameter default pattern matches anything

What is the type of the parameter t? Of the function? fun isValue (t:term) : bool = case t of Num n => true | Bool b => true | _ => false val isValue : term -> bool ML does type inference => you need not annotate functions yourself (but it can be helpful)

A type error fun isValue t = case t of Num _ => 1 | _ => false ex.sml: Error: types of rules don't agree [literal] earlier rule(s): term -> int this rule: term -> bool in rule: _ => false

A type error Actually, ML may give you several errors in a row: ex.sml: Error: types of rules don't agree [literal] earlier rule(s): term -> int this rule: term -> bool in rule: Num t2 => true ex.sml: Error: types of rules don't agree [literal] earlier rule(s): term -> int this rule: term -> bool in rule: _ => false

A very subtle error fun isValue t = case t of num => true | _ => false The code above type checks. But when we test it, the function always returns “true.” What has gone wrong?

A very subtle error fun isValue t = case t of num => true | _ => false The code above type checks. But when we test it, the function always returns “true.” What has gone wrong? -- num is not capitalized (and has no argument) -- ML treats it like a variable pattern (matches anything!)

Exceptions exception Error of string fun debug s : unit = raise (Error s)

Exceptions exception Error of string fun debug s : unit = raise (Error s) - debug "hello"; uncaught exception Error raised at: ex.sml: in SML interpreter:

Evaluator fun isValue t =... exception NoRule fun eval t = case t of Bool _ | Num _ => t |...

Evaluator... fun eval t = case t of Bool _ | Num _ => t | If(t1,t2,t3) => let val v = eval t1 in case v of Bool b => if b then (eval t2) else (eval t3) | _ => raise NoRule end let statement for remembering temporary results

Evaluator exception NoRule fun eval1 t = case t of Bool _ | Num _ =>... |... | Add (t1,t2) => case (eval v1, eval v2) of (Num n1, Num n2) => Num (n1 + n2) | (_,_) => raise NoRule

Finishing the Evaluator fun eval1 t = case t of... |... | Add (t1,t2) =>... | IsZero t =>... be sure your case is exhaustive

Finishing the Evaluator fun eval1 t = case t of... |... | Add (t1,t2) =>... What if we forgot a case?

Finishing the Evaluator ex.sml: Warning: match nonexhaustive (Bool _ | Zero) =>... If (t1,t2,t3) =>... Add (t1,t2) =>... fun eval1 t = case t of... |... | Add (t1,t2) =>... What if we forgot a case?

Demo Managing the source files for the interpreter

More on lists: Map fun map f l = case l of nil => [] l x :: l => (f x) :: (map f l) applies the function f to every element in the list - fun add1 x = x + 1; - map add1 [1,2,3]; > val it = [2,3,4] : int list

More on lists: Fold fun fold f init l = case l of nil => init | x :: l => f (x, fold f init l) applies function f (x, y) on the elements of l and the result from previous application recursively - fun sum (x, y) = x + y; - foldr sum 0 [1,2,3,4]; val it = 10 : int