CSC324 Functional Programming Typing, Exceptions in ML
|
|
- Caitlin Fleming
- 6 years ago
- Views:
Transcription
1 CSC324 Functional Programming Typing, Exceptions in ML Afsaneh Fazly 1 Winter with many thanks to Anya Tafliovich, Gerald Penn, Sheila McIlraith, Wael Aboelsaddat, Tony Bonner, Eric Joanis, Suzanne Stevenson.
2 type synonyms We can give existing types new names. Syntax: type new type = ty new type becomes an alias (a synonym) for the existing type ty. -type float = real; type float = real -type count = int and average = real; type count = int type average = real -val f : float = 2.3; val f = 2.3: float -val i = 3 : count; val i = 3: count
3 3 type synonyms But notice float, real, and average are all of the same base type, i.e., real: -val f : float = 2.3; val f = 2.3 : float -val a = f : average; val a = 2.3 : average -val sum = a+f; val sum = 4.6 : average -val sum = f+a; val sum = 4.6 : float
4 4 user-defined datatypes General Syntax: datatype new_type = Cons1 of type1 Cons2 of type2... ConsN of typen Defines a new type called new type. type1,...,typen are previously defined types. Cons1,...,ConsN are constructors. They are used to create a value of the type new type. of type is omitted if a constructor does not need any argument (such constructors are called constants).
5 enumerated types All constructors are constants (no argument), e.g.: -datatype color = Red Blue Green; datatype color = Blue Green Red -val c = Red; val c = Red : color -fun colorstr Red = "red" colorstr Blue = "blue" colorstr Green= "green"; val colorstr = fn : color -> string -colorstr c; val it = "red" : string
6 6 enumerated types How would you implement this in Python?
7 enumerated types How would you implement this in Python? class Enum(set): def getattr (self, name): if name in self: return name raise AttributeError color = Enum(["Red", "Blue", "Green"]) animal = Enum(["Dog", "Cat"]) print color.green, animal.dog Note: a class in Python (Java) essentially defines a new data type.
8 8 Create union of different types: datatype number = variant types
9 9 Create union of different types: variant types datatype number = R of real I of int; val n1 = I 2; val n2 = R 3.0; val lst = [R 2.2, I 3, I 4, R 0.1]; (* val lst = [R 2.2,I 3,I 4,R 0.1] : number list *) Note: a variant type is a non-specific type, e.g., number may hold a real or an integer.
10 10 variant types datatype number = R of real I of int; val lst = [R 2.2, I 3, I 4, R 0.1]; Write a function sumints that takes a number list and returns the sum of the integers:
11 variant types datatype number = R of real I of int; val lst = [R 2.2, I 3, I 4, R 0.1]; Write a function sumints that takes a number list and returns the sum of the integers: fun sumints [] = 0 sumints ((I x)::rest) = x + sumints rest sumints ((R x)::rest) = sumints rest; sumints : number list -> int; sumints lst; (* val it = 7 : int *)
12 12 recursive types Recursive types are good for defining dynamic data structures, e.g., a linked list:
13 13 recursive types Recursive types are good for defining dynamic data structures, e.g., a linked list: datatype llist = Nil Node of int * llist;
14 recursive types Recursive types are good for defining dynamic data structures, e.g., a linked list: datatype llist = Nil Node of int * llist; (* constructing instances of the linked list *) val x = Nil; val y = Node(5,Nil); val z = Node(3, Node(2, Node(1,Nil)));
15 recursive types in Python class LinkedList: def init (): creates an initial linked list self.first = LinkedList. Node() def addnode(element):... class Node: private node obj: element + pointer to next Node def init (self, element=none): self.element = element self.next = None def hasnext(self):... def getnext(self):... def setnext(self, nextnode):......
16 16 recursive types datatype llist = Nil Node of int * llist; val z = Node(3, Node(2, Node(1,Nil))); Write a function len that takes a llist and returns its length.
17 recursive types datatype llist = Nil Node of int * llist; val z = Node(3, Node(2, Node(1,Nil))); Write a function len that takes a llist and returns its length. (* length of a linked list *) fun len Nil = 0 len (Node (_,xs)) = 1 + len xs; len : llist -> int len z; val it = 3 : int
18 recursive types What about a polymorphic linked list?
19 recursive types What about a polymorphic linked list? Use a type variable. Remember type variables: a any type a any type for which equality is defined
20 recursive types What about a polymorphic linked list? Use a type variable. Remember type variables: a any type a any type for which equality is defined datatype a llist = Nil Node of a * ( a llist);
21 20 recursive types A polymorphic linked list: datatype a llist = Nil Node of a * ( a llist); val y = Node(5,Nil); (* int llist *) val z = Node("A", Node("B",Nil)); (* string llist *)
22 recursive types datatype a llist = Nil Node of a * ( a llist); fun len Nil = 0 len (Node (_,xs)) = 1 + len xs; len : a llist -> int len y; (* val it = 1 : int *) len z; (* val it = 2 : int *)
23 22 recursive types Example: a polymorphic binary tree.
24 23 recursive types Example: a polymorphic binary tree. datatype a tree = Leaf of a Node of a * a tree * a tree;
25 24 recursive types Example: a polymorphic binary tree. datatype a tree = Leaf of a Node of a * a tree * a tree; Function for summing-up all values in an int tree:
26 25 recursive types Example: a polymorphic binary tree. datatype a tree = Leaf of a Node of a * a tree * a tree; Function for summing-up all values in an int tree: fun sumt (Leaf x) = x sumt (Node(x,ltree,rtree)) = x + sumt(ltree) + sumt(rtree);
27 admin notes Midterm Exam: Date: Monday Feb. 25, Duration: 50 minutes, from 2:10pm to 3pm. Location: UofT Examination Centre, Room 300. Topic: Everything we have covered, including today s lecture. Office Hours for Reading Week: Friday, Feb. 22, 2013, 2 4pm, BA No other office hours during the reading week. Tutorial Friday Feb. 15: One tutorial session in the lecture room, BA 1190.
28 more admin notes A1 marks are now available through CDF secure website. Assignment#3 (ML) is posted. Sample midterm exam, and sample solutions to A1 and A2 are now available. Please see Announcements on the course website for more information.
29 recursive types Example: Tree representation of simple mathematical expressions. ( ) + ((-1) + 4) * 7) add add mult abs 2 add 7 neg 3 neg 4 1 What is the datatype we need? 28
30 recursive types datatype math_tree = Leaf of int Unary of (int -> int) * math_tree Binary of (int * int -> int) * math_tree * math_tree
31 recursive types datatype math_tree = Leaf of int Unary of (int -> int) * math_tree Binary of (int * int -> int) * math_tree * math_tree Instances of type math tree: Leaf 3; Unary(op ~, Leaf 3); Binary(op +, Leaf 4, Unary(op ~, Leaf 3));
32 The tree in the figure: recursive types val t = Binary(op +, Binary(op +, Unary((fn x => if x > 0 then x else ~x), Unary (op ~, Leaf 3)), Leaf 2), Binary(op *, Binary(op +, Unary(op ~, Leaf 1), Leaf 4), Leaf 7))
33 32 recursive types Define a function eval: math tree -> int that returns the result of evaluatng a math tree:
34 recursive types Define a function eval: math tree -> int that returns the result of evaluatng a math tree: fun eval (Leaf n) = n eval (Unary (f,t)) = f (eval t) eval (Binary (f,l,r)) = f (eval l,eval r); eval : math_tree -> int - eval t; val it = 26 : int
35 34 recursive types in Python/Java How would you define the datatype math tree and the function eval in Python or Java?
36 34 recursive types in Python/Java How would you define the datatype math tree and the function eval in Python or Java? What differences do you see between ML and Python/Java?
37 mutual recursion in ML Let s mimic the Scheme definitions of even and odd: fun even 0 = true even x = odd (x - 1); fun odd 0 = false odd x = even (x - 1); Error: unbound variable or constructor: odd
38 36 Use the keyword and. fun even 0 = true even x = odd (x - 1) and odd 0 = false odd x = even (x - 1); even : int -> bool; odd : int -> bool mutual recursion in ML even 42; (* val it = true : bool *) odd 42; (* val it = false : bool *)
39 37 mutually recursive types Example: a binary tree with labeled branches:
40 38 mutually recursive types Example: a binary tree with labeled branches: datatype a tree = Empty Node of a branch * a branch and a branch = Branch of a * a tree;
41 mutually recursive types datatype a tree = Empty Node of a branch * a branch and a branch = Branch of a * a tree; Instances of tree: Empty; Node(Branch(7,Empty), Branch(8,Empty)); Node(Branch(1,Empty), Branch(6, Node(Branch(7,Empty), Branch(8,Empty))));
42 The tree in the figure: mutually recursive types val lt = Node(Branch(1, Node(Branch(2, Empty), Branch(3, Node(Branch(4, Empty), Branch(5, Empty))))), Branch(6, Node(Branch(7, Empty), Branch(8, Empty))));
43 41 mutually recursive types datatype a tree = Empty Node of a branch * a branch and a branch = Branch of a * a tree Define listtree that returns the list of branch labels, in order:
44 mutually recursive types datatype a tree = Empty Node of a branch * a branch and a branch = Branch of a * a tree Define listtree that returns the list of branch labels, in order: fun listtree Empty = [] listtree (Node (l,r)) = (listbranch (listbranch r) and listbranch (Branch (b,t)) = b :: (listtree t); listtree : a tree -> a list; listbranch : a branch -> a list listtree t; (* val it = [1,2,3,4,5,6,7,8] : int list *)
45 Mutually Recursive Types We could also define: fun listtree Empty = [] listtree (Node(Branch(x,tL),Branch(y,tR))) = (x :: (y :: listtree(tr));
46 recursive types 1. A powerful tool for constructing new types. 2. The structure of the datatype suggests the structure of the recursive function on the datatype structural recursion.
47 45 notes: associativity of function application Function application is left-associative: Example: - reverse 1::[2,3]; f g h == (f g) h... Error: operator and operand don t agree operator domain: Z list operand: int in expression: reverse 1 - reverse (1::[2,3]); val it = [3,2,1] : int list
48 using let in ML fun sumcube n = let fun cube x = x * x * x in if n = 0 then 0 else cube (n) + sumcube (n-1) end; Is it a good idea?
49 using let in ML fun sumcube n = let fun cube x = x * x * x in if n = 0 then 0 else cube (n) + sumcube (n-1) end; Is it a good idea? cube is redefined every recursive call.
50 Better idea: using let in ML fun sumcube n = let fun cube x = x * x * x; fun sumc 0 = 0 sumc m = cube m + sumc (m-1) in sumc n end;
51 49 Example: using let in ML let val y=2 in if (y > (let val y=3 in y*y end)) then y else ~y end; What is the value? Why?
52 Example: using let in ML let val y=2 in if (y > (let val y=3 in y*y end)) then y else ~y end; What is the value? Why? let val y=2 in if (y > (let val y=3 in y*y end)) then y else ~y end; Indentation matters!
53 51 Example: Using let in ML let val x=2 in let fun f(x) = x + 1 in f(x) end end; What is the value? Why?
54 Example: Using let in ML let val x=2 in let fun f(x) = x + 1 in f(x) end end; What is the value? Why? let in val x = 2 let in end end; fun f(x) = x + 1 f(x)
55 Example: Using let in ML let val y=3 in let fun f(x) = x + y in let val y=2 in f(y) end end end; What is the value? Why?
56 54 SML exceptions ML s exceptions (similar to the ones in Java or Python) provide a uniform way to handle errors, and eliminate the need for ad hoc, special exceptional return values from functions. When encountering a special case, raise an exception. The caller will catch/handle the exception and will take care of it. Primitive (built-in) exceptions: 3 div 0 (* raises Div *) hd nil (* raises Empty *)
57 SML user-defined exceptions Defining an exception: exception <name> of <type> Raising an exception: raise <name> <arg>
58 SML user-defined exceptions exception factneg; fun robustfact n = let fun fact 0 = 1 fact n = n * fact (n-1); in if n < 0 then raise factneg else fact n end; robustfact 5; (* val it = 120 : int *) robustfact ~5; (* uncaught exception factneg *)
59 SML exceptions Exceptions can have arguments, just like datatypes: exception factneg of int; fun robustfact n= let fun fact 0 = 1 fact n = n * fact (n-1); in if n < 0 then raise factneg n else fact n end;
60 Handling exceptions: SML exceptions <expr> handle <match1> => <expr1> <match2> => <expr2>... <matchn> => <exprn> exceptions raised within <expr> are handled by the <match> expression. Any restrictions on types?
61 SML exceptions fun printfact n = print (Int.toString(robustFact n)^"\n") handle factneg x => print ("printfact "^(Int.toString x)^ ": argument must be >= 0\n"); (* val printfact = fn : int -> unit *) printfact ~5; (* printfact ~5: argument must be >= 0 val it = () : unit *)
62 exceptions Why do we need exceptions in a strongly typed language?
63 60 exceptions Why do we need exceptions in a strongly typed language? Type-checker only checks types of parameters, not their values.
64 60 exceptions Why do we need exceptions in a strongly typed language? Type-checker only checks types of parameters, not their values. In languages w/o exception handling, when an exception occurs:
65 60 exceptions Why do we need exceptions in a strongly typed language? Type-checker only checks types of parameters, not their values. In languages w/o exception handling, when an exception occurs: control goes to the OS and the program is terminated, or
66 60 exceptions Why do we need exceptions in a strongly typed language? Type-checker only checks types of parameters, not their values. In languages w/o exception handling, when an exception occurs: control goes to the OS and the program is terminated, or special code must be written to handle exceptions (e.g., pass special parameter, or use return value of procedure to indicate status of program, etc.)
67 60 exceptions Why do we need exceptions in a strongly typed language? Type-checker only checks types of parameters, not their values. In languages w/o exception handling, when an exception occurs: control goes to the OS and the program is terminated, or special code must be written to handle exceptions (e.g., pass special parameter, or use return value of procedure to indicate status of program, etc.) In contrast, with exception handling, programs can systematically fix the problem and continue, if desirable.
68 61 exceptions datatype a tree = Empty Leaf of a Node of a tree * a tree; Define function left subtree: a tree -> a tree
69 62 exceptions datatype a tree = Empty Leaf of a Node of a tree * a tree; exception empty_tree and no_subtree and no_left; fun left_subtree (Empty) = raise empty_tree left_subtree (Leaf x) = raise no_subtree left_subtree (Node(Empty,r)) = raise no_left left_subtree (Node(l,r)) = l; Need to handle exceptions.
70 exceptions datatype a tree = Empty Leaf of a Node of a tree * a tree; exception empty_tree and no_subtree and no_left; fun left_subtree (Empty) = raise empty_tree left_subtree (Leaf x) = raise no_subtree left_subtree (Node(Empty,r)) = raise no_left left_subtree (Node(l,r)) = l; fun robust_left_subtree (tree) = left_subtree(tree) handle empty_tree => Empty no_subtree => Empty no_left => Empty;
71 Using let... exceptions fun robust_left_subtree (tree) = let fun left_subtree (Empty) = raise empty_tree left_subtree (Leaf x) = raise no_subtree left_subtree (Node(Empty,r)) = raise no_left left_subtree (Node(l,r)) = l; in left_subtree(tree) handle empty_tree => Empty no_subtree => Empty no_left => Empty end;
72 65 ML functional: recursion pattern matching higher-order functions strong type system: type safe static type checking type inference built-in types type synonyms user-defined (abstract) data types: enumerated, variant, recursive, mutually recursive types exception handling static scoping (dynamic scoping for exception handling) garbage collection, immutable data types, updatable references
CSCC24 Functional Programming Typing, Scope, Exceptions ML
CSCC24 Functional Programming Typing, Scope, Exceptions ML Carolyn MacLeod 1 winter 2012 1 Based on slides by Anya Tafliovich, with many thanks to Gerald Penn and Sheila McIlraith. motivation Consider
More informationCSC324- TUTORIAL 5. Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides
CSC324- TUTORIAL 5 ML Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides Assignment 1 2 More questions were added Questions regarding the assignment? Starting ML Who am I? Shems Saleh
More informationOCaml. ML Flow. Complex types: Lists. Complex types: Lists. The PL for the discerning hacker. All elements must have same type.
OCaml The PL for the discerning hacker. ML Flow Expressions (Syntax) Compile-time Static 1. Enter expression 2. ML infers a type Exec-time Dynamic Types 3. ML crunches expression down to a value 4. Value
More informationInductive Data Types
Inductive Data Types Lars-Henrik Eriksson Functional Programming 1 Original slides by Tjark Weber Lars-Henrik Eriksson (UU) Inductive Data Types 1 / 42 Inductive Data Types Today Today New names for old
More informationCSE 130 [Winter 2014] Programming Languages
CSE 130 [Winter 2014] Programming Languages Introduction to OCaml (Continued) Ravi Chugh! Jan 14 Announcements HW #1 due Mon Jan 20 Post questions/discussion to Piazza Check Piazza for TA/Tutor lab hours
More informationExercises on ML. Programming Languages. Chanseok Oh
Exercises on ML Programming Languages Chanseok Oh chanseok@cs.nyu.edu Dejected by an arcane type error? - foldr; val it = fn : ('a * 'b -> 'b) -> 'b -> 'a list -> 'b - foldr (fn x=> fn y => fn z => (max
More informationProgramming Languages
CSE 130 : Winter 2013 Programming Languages Lecture 3: Crash Course, Datatypes Ranjit Jhala UC San Diego 1 Story So Far... Simple Expressions Branches Let-Bindings... Today: Finish Crash Course Datatypes
More informationHaske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell
Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dk The most popular purely functional, lazy programming language Functional programming language : a program
More informationCSCI-GA Scripting Languages
CSCI-GA.3033.003 Scripting Languages 12/02/2013 OCaml 1 Acknowledgement The material on these slides is based on notes provided by Dexter Kozen. 2 About OCaml A functional programming language All computation
More informationAn introduction introduction to functional functional programming programming using usin Haskell
An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dkau Haskell The most popular p purely functional, lazy programming g language Functional programming language : a program
More informationProgramming Languages
CSE 130 : Fall 2008 Programming Languages Lecture 2: A Crash Course in ML Ranjit Jhala UC San Diego News On webpage: Suggested HW #1, sample for Quiz #1 on Thu PA #1 (due next Fri 10/10) No make-up quizzes
More informationMini-ML. CS 502 Lecture 2 8/28/08
Mini-ML CS 502 Lecture 2 8/28/08 ML This course focuses on compilation techniques for functional languages Programs expressed in Standard ML Mini-ML (the source language) is an expressive core subset of
More informationComputer Science CSC324 Wednesday February 13, Homework Assignment #3 Due: Thursday February 28, 2013, by 10 p.m.
Computer Science CSC324 Wednesday February 13, 2013 St. George Campus University of Toronto Homework Assignment #3 Due: Thursday February 28, 2013, by 10 p.m. Silent Policy A silent policy takes effect
More informationNews. Programming Languages. Complex types: Lists. Recap: ML s Holy Trinity. CSE 130: Spring 2012
News CSE 130: Spring 2012 Programming Languages On webpage: Suggested HW #1 PA #1 (due next Fri 4/13) Lecture 2: A Crash Course in ML Please post questions to Piazza Ranjit Jhala UC San Diego Today: A
More informationRecap from last time. Programming Languages. CSE 130 : Fall Lecture 3: Data Types. Put it together: a filter function
CSE 130 : Fall 2011 Recap from last time Programming Languages Lecture 3: Data Types Ranjit Jhala UC San Diego 1 2 A shorthand for function binding Put it together: a filter function # let neg = fun f
More informationStandard ML. Data types. ML Datatypes.1
Standard ML Data types ML Datatypes.1 Concrete Datatypes The datatype declaration creates new types These are concrete data types, not abstract Concrete datatypes can be inspected - constructed and taken
More informationProgramming Languages
CSE 130: Spring 2010 Programming Languages Lecture 2: A Crash Course in ML Ranjit Jhala UC San Diego News On webpage: Suggested HW #1 PA #1 (due next Wed 4/9) Please post questions to WebCT Today: A crash
More informationCS558 Programming Languages
CS558 Programming Languages Winter 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Values and Types We divide the universe of values according to types A type is a set of values and
More informationProgramming Languages
CSE 130 : Spring 2011 Programming Languages Lecture 3: Crash Course Ctd, Expressions and Types Ranjit Jhala UC San Diego A shorthand for function binding # let neg = fun f -> fun x -> not (f x); # let
More informationPlan (next 4 weeks) 1. Fast forward. 2. Rewind. 3. Slow motion. Rapid introduction to what s in OCaml. Go over the pieces individually
Plan (next 4 weeks) 1. Fast forward Rapid introduction to what s in OCaml 2. Rewind 3. Slow motion Go over the pieces individually History, Variants Meta Language Designed by Robin Milner @ Edinburgh Language
More informationLecture 19: Functions, Types and Data Structures in Haskell
The University of North Carolina at Chapel Hill Spring 2002 Lecture 19: Functions, Types and Data Structures in Haskell Feb 25 1 Functions Functions are the most important kind of value in functional programming
More informationRecap: ML s Holy Trinity
Recap: ML s Holy Trinity Expressions (Syntax) Exec-time Dynamic Values (Semantics) Compile-time Static Types 1. Programmer enters expression 2. ML checks if expression is well-typed Using a precise set
More informationLists. Michael P. Fourman. February 2, 2010
Lists Michael P. Fourman February 2, 2010 1 Introduction The list is a fundamental datatype in most functional languages. ML is no exception; list is a built-in ML type constructor. However, to introduce
More informationProgramming Languages
CSE 130: Fall 2009 Programming Languages Lecture 2: A Crash Course in ML News On webpage: Suggested HW #1 PA #1 (due next Fri 10/9) Technical issues installing Ocaml - should be resolved soon! Ranjit Jhala
More informationCSE 130 Programming Languages. Lecture 3: Datatypes. Ranjit Jhala UC San Diego
CSE 130 Programming Languages Lecture 3: Datatypes Ranjit Jhala UC San Diego News? PA #2 (coming tonight) Ocaml-top issues? Pleas post questions to Piazza Recap: ML s Holy Trinity Expressions (Syntax)
More informationCSCC24 Functional Programming Scheme Part 2
CSCC24 Functional Programming Scheme Part 2 Carolyn MacLeod 1 winter 2012 1 Based on slides from Anya Tafliovich, and with many thanks to Gerald Penn and Prabhakar Ragde. 1 The Spirit of Lisp-like Languages
More informationCS 320: Concepts of Programming Languages
CS 320: Concepts of Programming Languages Wayne Snyder Computer Science Department Boston University Lecture 04: Basic Haskell Continued o Polymorphic Types o Type Inference with Polymorphism o Standard
More informationINTERPRETERS 8. 1 Calculator COMPUTER SCIENCE 61A. November 3, 2016
INTERPRETERS 8 COMPUTER SCIENCE 61A November 3, 2016 1 Calculator We are beginning to dive into the realm of interpreting computer programs that is, writing programs that understand other programs. In
More informationHandout 2 August 25, 2008
CS 502: Compiling and Programming Systems Handout 2 August 25, 2008 Project The project you will implement will be a subset of Standard ML called Mini-ML. While Mini- ML shares strong syntactic and semantic
More informationCSE 341 Section 5. Winter 2018
CSE 341 Section 5 Winter 2018 Midterm Review! Variable Bindings, Shadowing, Let Expressions Boolean, Comparison and Arithmetic Operations Equality Types Types, Datatypes, Type synonyms Tuples, Records
More informationRecap: ML s Holy Trinity. Story So Far... CSE 130 Programming Languages. Datatypes. A function is a value! Next: functions, but remember.
CSE 130 Programming Languages Recap: ML s Holy Trinity Expressions (Syntax) Exec-time Dynamic Values (Semantics) Datatypes Compile-time Static Types Ranjit Jhala UC San Diego 1. Programmer enters expression
More informationCSE 130 Programming Languages. Datatypes. Ranjit Jhala UC San Diego
CSE 130 Programming Languages Datatypes Ranjit Jhala UC San Diego Recap: ML s Holy Trinity Expressions (Syntax) Exec-time Dynamic Values (Semantics) Compile-time Static Types 1. Programmer enters expression
More informationAnnouncements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am.
The current topic: Scheme! Introduction! Object-oriented programming: Python Functional programming: Scheme! Introduction! Numeric operators, REPL, quotes, functions, conditionals! Function examples, helper
More informationHigher-Order Functions
Higher-Order Functions Tjark Weber Functional Programming 1 Based on notes by Pierre Flener, Jean-Noël Monette, Sven-Olof Nyström Tjark Weber (UU) Higher-Order Functions 1 / 1 Tail Recursion http://xkcd.com/1270/
More informationSML A F unctional Functional Language Language Lecture 19
SML A Functional Language Lecture 19 Introduction to SML SML is a functional programming language and acronym for Standard d Meta Language. SML has basic data objects as expressions, functions and list
More informationProcessadors de Llenguatge II. Functional Paradigm. Pratt A.7 Robert Harper s SML tutorial (Sec II)
Processadors de Llenguatge II Functional Paradigm Pratt A.7 Robert Harper s SML tutorial (Sec II) Rafael Ramirez Dep Tecnologia Universitat Pompeu Fabra Paradigm Shift Imperative Paradigm State Machine
More informationIf we have a call. Now consider fastmap, a version of map that uses futures: Now look at the call. That is, instead of
If we have a call (map slow-function long-list where slow-function executes slowly and long-list is a large data structure, we can expect to wait quite a while for computation of the result list to complete.
More informationLecture #23: Conversion and Type Inference
Lecture #23: Conversion and Type Inference Administrivia. Due date for Project #2 moved to midnight tonight. Midterm mean 20, median 21 (my expectation: 17.5). Last modified: Fri Oct 20 10:46:40 2006 CS164:
More informationConversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = "Hello";
Lecture #23: Conversion and Type Inference Administrivia. Due date for Project #2 moved to midnight tonight. Midterm mean 20, median 21 (my expectation: 17.5). In Java, this is legal: Object x = "Hello";
More informationIntroduction to OCaml
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
More informationStructure and Interpretation of Computer Programs
CS 6A Fall 206 Structure and Interpretation of Computer Programs Final Solutions INSTRUCTIONS You have hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator,
More informationHaskell 98 in short! CPSC 449 Principles of Programming Languages
Haskell 98 in short! n Syntax and type inferencing similar to ML! n Strongly typed! n Allows for pattern matching in definitions! n Uses lazy evaluation" F definition of infinite lists possible! n Has
More informationSummer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define
CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,
More informationDatatype declarations
Datatype declarations datatype suit = HEARTS DIAMONDS CLUBS SPADES datatype a list = nil (* copy me NOT! *) op :: of a * a list datatype a heap = EHEAP HEAP of a * a heap * a heap type suit val HEARTS
More informationProgramming in Standard ML: Continued
Programming in Standard ML: Continued Specification and Verification with Higher-Order Logic Arnd Poetzsch-Heffter (Slides by Jens Brandt) Software Technology Group Fachbereich Informatik Technische Universität
More informationSCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017
SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,
More informationCOSE212: Programming Languages. Lecture 3 Functional Programming in OCaml
COSE212: Programming Languages Lecture 3 Functional Programming in OCaml Hakjoo Oh 2017 Fall Hakjoo Oh COSE212 2017 Fall, Lecture 3 September 18, 2017 1 / 44 Why learn ML? Learning ML is a good way of
More informationA First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1
A First Look at ML Chapter Five Modern Programming Languages, 2nd ed. 1 ML Meta Language One of the more popular functional languages (which, admittedly, isn t saying much) Edinburgh, 1974, Robin Milner
More informationCS558 Programming Languages
CS558 Programming Languages Winter 2018 Lecture 7b Andrew Tolmach Portland State University 1994-2018 Dynamic Type Checking Static type checking offers the great advantage of catching errors early And
More informationTyped Racket: Racket with Static Types
Typed Racket: Racket with Static Types Version 5.0.2 Sam Tobin-Hochstadt November 6, 2010 Typed Racket is a family of languages, each of which enforce that programs written in the language obey a type
More informationA Second Look At ML. Chapter Seven Modern Programming Languages, 2nd ed. 1
A Second Look At ML Chapter Seven Modern Programming Languages, 2nd ed. 1 Outline Patterns Local variable definitions A sorting example Chapter Seven Modern Programming Languages, 2nd ed. 2 Two Patterns
More informationSpring 2018 Discussion 7: March 21, Introduction. 2 Primitives
CS 61A Scheme Spring 2018 Discussion 7: March 21, 2018 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme
More informationSo what does studying PL buy me?
So what does studying PL buy me? Enables you to better choose the right language but isn t that decided by libraries, standards, and my boss? Yes. Chicken-and-egg. My goal: educate tomorrow s tech leaders
More informationThe type checker will complain that the two branches have different types, one is string and the other is int
1 Intro to ML 1.1 Basic types Need ; after expression - 42 = ; val it = 42 : int - 7+1; val it = 8 : int Can reference it - it+2; val it = 10 : int - if it > 100 then "big" else "small"; val it = "small"
More informationSCHEME AND CALCULATOR 5b
SCHEME AND CALCULATOR 5b COMPUTER SCIENCE 6A July 25, 203 In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,
More informationCS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1
CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1 Goals of this tutorial You should be able to... understand
More informationInterpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions. 1 Calculator. calc> (+ 2 2) 4
CS 61A Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions 1 Calculator We are beginning to dive into the realm of interpreting computer programs that is, writing programs that
More informationFall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives
CS 6A Scheme Fall 207 Discussion 7: October 25, 207 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write
More informationChapter 3 Linear Structures: Lists
Plan Chapter 3 Linear Structures: Lists 1. Lists... 3.2 2. Basic operations... 3.4 3. Constructors and pattern matching... 3.5 4. Polymorphism... 3.8 5. Simple operations on lists... 3.11 6. Application:
More information9/23/2014. Function: it s easy and it is fun Local Function & Composite Function Polymorphic function I/O Structure and signature
Dr A Sahu Dept of Computer Science & Engeerg IIT Guwahati Function: it s easy and it is fun Local Function & Composite Function Polymorphic function I/O Structure and signature Operator head hd and tail
More informationCSC/MAT-220: Lab 6. Due: 11/26/2018
CSC/MAT-220: Lab 6 Due: 11/26/2018 In Lab 2 we discussed value and type bindings. Recall, value bindings bind a value to a variable and are intended to be static for the life of a program. Type bindings
More informationCSC324 Principles of Programming Languages
CSC324 Principles of Programming Languages http://mcs.utm.utoronto.ca/~324 November 14, 2018 Today Final chapter of the course! Types and type systems Haskell s type system Types Terminology Type: set
More informationOCaml. History, Variants. ML s holy trinity. Interacting with ML. Base type: Integers. Base type: Strings. *Notes from Sorin Lerner at UCSD*
OCaml 1. Introduction Rapid introduction to what s in OCaml 2. Focus on Features Individually as Needed as Semester Progresses *Notes from Sorin Lerner at UCSD* History, Variants Meta Language Designed
More informationStructure and Interpretation of Computer Programs
CS 61A Fall 2016 Structure and Interpretation of Computer Programs Final INSTRUCTIONS You have 3 hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator, except
More informationTypes and Programming Languages. Lecture 5. Extensions of simple types
Types and Programming Languages Lecture 5. Extensions of simple types Xiaojuan Cai cxj@sjtu.edu.cn BASICS Lab, Shanghai Jiao Tong University Fall, 2016 Coming soon Simply typed λ-calculus has enough structure
More informationCS558 Programming Languages
CS558 Programming Languages Fall 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Type Inference Some statically typed languages, like ML (and to a lesser extent Scala), offer alternative
More informationFall Lecture 3 September 4. Stephen Brookes
15-150 Fall 2018 Lecture 3 September 4 Stephen Brookes Today A brief remark about equality types Using patterns Specifying what a function does equality in ML e1 = e2 Only for expressions whose type is
More informationCSE 341, Spring 2011, Final Examination 9 June Please do not turn the page until everyone is ready.
CSE 341, Spring 2011, Final Examination 9 June 2011 Please do not turn the page until everyone is ready. Rules: The exam is closed-book, closed-note, except for one side of one 8.5x11in piece of paper.
More informationExercise 1 ( = 24 points)
1 Exercise 1 (4 + 5 + 4 + 6 + 5 = 24 points) The following data structure represents polymorphic binary trees that contain values only in special Value nodes that have a single successor: data Tree a =
More informationFunctional programming Primer I
Functional programming Primer I COS 320 Compiling Techniques Princeton University Spring 2016 Lennart Beringer 1 Characteristics of functional programming Primary notions: functions and expressions (not
More informationCSE341, Spring 2013, Final Examination June 13, 2013
CSE341, Spring 2013, Final Examination June 13, 2013 Please do not turn the page until 8:30. Rules: The exam is closed-book, closed-note, except for both sides of one 8.5x11in piece of paper. Please stop
More informationCSci 4223 Lecture 12 March 4, 2013 Topics: Lexical scope, dynamic scope, closures
CSci 4223 Lecture 12 March 4, 2013 Topics: Lexical scope, dynamic scope, closures 1 Lexical Scope SML, and nearly all modern languages, follow the Rule of Lexical Scope: the body of a function is evaluated
More informationNote that pcall can be implemented using futures. That is, instead of. we can use
Note that pcall can be implemented using futures. That is, instead of (pcall F X Y Z) we can use ((future F) (future X) (future Y) (future Z)) In fact the latter version is actually more parallel execution
More informationAccording to Larry Wall (designer of PERL): a language by geniuses! for geniuses. Lecture 7: Haskell. Haskell 98. Haskell (cont) - Type-safe!
Lecture 7: Haskell CSC 131 Fall, 2014 Kim Bruce According to Larry Wall (designer of PERL): a language by geniuses for geniuses He s wrong at least about the latter part though you might agree when we
More informationIntroduction to ML. Based on materials by Vitaly Shmatikov. General-purpose, non-c-like, non-oo language. Related languages: Haskell, Ocaml, F#,
Introduction to ML Based on materials by Vitaly Shmatikov slide 1 ML General-purpose, non-c-like, non-oo language Related languages: Haskell, Ocaml, F#, Combination of Lisp and Algol-like features (1958)
More informationINTERPRETERS AND TAIL CALLS 9
INTERPRETERS AND TAIL CALLS 9 COMPUTER SCIENCE 61A April 9, 2015 We are beginning to dive into the realm of interpreting computer programs that is, writing programs that understand other programs. In order
More informationCSCI-GA Final Exam
CSCI-GA 2110-003 - Final Exam Instructor: Thomas Wies Name: Sample Solution ID: You have 110 minutes time. There are 7 assignments and you can reach 110 points in total. You can solve the exercises directly
More informationLecture #13: Type Inference and Unification. Typing In the Language ML. Type Inference. Doing Type Inference
Lecture #13: Type Inference and Unification Typing In the Language ML Examples from the language ML: fun map f [] = [] map f (a :: y) = (f a) :: (map f y) fun reduce f init [] = init reduce f init (a ::
More informationCS 11 Ocaml track: lecture 2
Today: CS 11 Ocaml track: lecture 2 comments algebraic data types more pattern matching records polymorphic types ocaml libraries exception handling Previously... ocaml interactive interpreter compiling
More informationA Brief Introduction to Standard ML
A Brief Introduction to Standard ML Specification and Verification with Higher-Order Logic Arnd Poetzsch-Heffter (Slides by Jens Brandt) Software Technology Group Fachbereich Informatik Technische Universität
More informationFunctors signature Order = sig functor name type elem (structname:signature) = structure definition; val le : elem*elem -> bool end; elem
Functors The general form of a functor is functor name (structname:signature) = structure definition; This functor will create a specific version of the structure definition using the structure parameter
More informationFall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives
CS 6A Scheme Fall 208 Discussion 8: October 24, 208 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write
More informationProgramming Languages
CSE 130: Spring 2010 Programming Languages Lecture 3: Epressions and Types Ranjit Jhala UC San Diego A Problem fun -> +1 Can functions only have a single parameter? A Solution: Simultaneous Binding Parameter
More informationGADTs. Wouter Swierstra and Alejandro Serrano. Advanced functional programming - Lecture 7. [Faculty of Science Information and Computing Sciences]
GADTs Advanced functional programming - Lecture 7 Wouter Swierstra and Alejandro Serrano 1 Today s lecture Generalized algebraic data types (GADTs) 2 A datatype data Tree a = Leaf Node (Tree a) a (Tree
More informationCSE 505. Lecture #9. October 1, Lambda Calculus. Recursion and Fixed-points. Typed Lambda Calculi. Least Fixed Point
Lambda Calculus CSE 505 Lecture #9 October 1, 2012 Expr ::= Var λ Var. Expr (Expr Expr) Key Concepts: Bound and Free Occurrences Substitution, Reduction Rules: α, β, η Confluence and Unique Normal Form
More informationChapter 3 Linear Structures: Lists
Plan Chapter 3 Linear Structures: Lists 1. Two constructors for lists... 3.2 2. Lists... 3.3 3. Basic operations... 3.5 4. Constructors and pattern matching... 3.6 5. Simple operations on lists... 3.9
More informationLecture 2: SML Basics
15-150 Lecture 2: SML Basics Lecture by Dan Licata January 19, 2012 I d like to start off by talking about someone named Alfred North Whitehead. With someone named Bertrand Russell, Whitehead wrote Principia
More informationBegin at the beginning
Begin at the beginning Expressions (Syntax) Exec-time Dynamic Values (Semantics) Compile-time Static Types 1. Programmer enters expression 2. ML checks if expression is well-typed Using a precise set of
More informationRuby: Introduction, Basics
Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 3 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie
More informationCornell University 12 Oct Solutions. (a) [9 pts] For each of the 3 functions below, pick an appropriate type for it from the list below.
Cornell University 12 Oct 2006 Solutions 1. Types, Polymorphism [14 pts] (parts a b) (a) [9 pts] For each of the 3 functions below, pick an appropriate type for it from the list below. i. fun f x y = (y,
More informationCSE341: Programming Languages Lecture 11 Type Inference. Dan Grossman Spring 2016
CSE341: Programming Languages Lecture 11 Type Inference Dan Grossman Spring 2016 Type-checking (Static) type-checking can reject a program before it runs to prevent the possibility of some errors A feature
More informationOCaml Data CMSC 330: Organization of Programming Languages. User Defined Types. Variation: Shapes in Java
OCaml Data : Organization of Programming Languages OCaml 4 Data Types & Modules So far, we ve seen the following kinds of data Basic types (int, float, char, string) Lists Ø One kind of data structure
More informationCSE341, Fall 2011, Midterm Examination October 31, 2011
CSE341, Fall 2011, Midterm Examination October 31, 2011 Please do not turn the page until the bell rings. Rules: The exam is closed-book, closed-note, except for one side of one 8.5x11in piece of paper.
More informationNews. CSE 130: Programming Languages. Environments & Closures. Functions are first-class values. Recap: Functions as first-class values
CSE 130: Programming Languages Environments & Closures News PA 3 due THIS Friday (5/1) Midterm NEXT Friday (5/8) Ranjit Jhala UC San Diego Recap: Functions as first-class values Arguments, return values,
More informationGADTs. Alejandro Serrano. AFP Summer School. [Faculty of Science Information and Computing Sciences]
GADTs AFP Summer School Alejandro Serrano 1 Today s lecture Generalized algebraic data types (GADTs) 2 A datatype data Tree a = Leaf Node (Tree a) a (Tree a) This definition introduces: 3 A datatype data
More informationTyped Scheme: Scheme with Static Types
Typed Scheme: Scheme with Static Types Version 4.1.1 Sam Tobin-Hochstadt October 5, 2008 Typed Scheme is a Scheme-like language, with a type system that supports common Scheme programming idioms. Explicit
More informationTAIL RECURSION, SCOPE, AND PROJECT 4 11
TAIL RECURSION, SCOPE, AND PROJECT 4 11 COMPUTER SCIENCE 61A Noveber 12, 2012 1 Tail Recursion Today we will look at Tail Recursion and Tail Call Optimizations in Scheme, and how they relate to iteration
More informationAny questions. Say hello to OCaml. Say hello to OCaml. Why readability matters. History, Variants. Plan (next 4 weeks)
Any questions Say hello to OCaml? void sort(int arr[], int beg, int end){ if (end > beg + 1){ int piv = arr[beg]; int l = beg + 1; int r = end; while (l!= r-1){ if(arr[l]
More informationType Checking and Type Inference
Type Checking and Type Inference Principles of Programming Languages CSE 307 1 Types in Programming Languages 2 Static Type Checking 3 Polymorphic Type Inference Version: 1.8 17:20:56 2014/08/25 Compiled
More informationProgramming Languages and Techniques (CIS120)
Programming Languages and Techniques (CIS120) Lecture 10 February 5 th, 2016 Abstract types: sets Lecture notes: Chapter 10 What is the value of this expresssion? let f (x:bool) (y:int) : int = if x then
More information