# COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

Size: px
Start display at page:

## Transcription

1 COSE212: Programming Languages Lecture 3 Functional Programming in OCaml Hakjoo Oh 2017 Fall Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

2 Why learn ML? Learning ML is a good way of experiencing modern language features: functional programming: scala, java8, haskell, python, JavaScript, etc static type system: scala, java, haskell, etc automatic type inference: scala, haskell, etc pattern matching: scala, etc algebraic data types, module system, etc Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

3 Basics of the Language Expressions Names Functions Pattern matching Type inference Tuples and lists Data types Exceptions Write and run all examples in the slides by yourself! Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

4 An OCaml Program is an Expression Statement and expressions: A statement does something. An expression evaluates to a value. Programming languages can be classified into statement-oriented: C, C++, Java, Python, JavaScript, etc often called imperative languages expression-oriented: ML, Haskell, Scala, Lisp, etc often called functional languages Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

5 Arithmetic Expressions Arithmetic expressions evaluate to numbers: e.g., 1+2*3, 1+5, 7 Try to evaluate expressions in the REPL: # 1+2*3;; - : int = 7 Arithmetic operators on integers: a + b a - b a * b a / b a mod b addition subtraction multiplication divide a by b, returning the whole part divide a by b, returning the remaining part Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

6 Boolean Expressions Boolean expressions evaluate to boolean values (i.e., true, false). Try to evaluate boolean expressions: # true;; - : bool = true # true;; - : bool = true # 1 > 2;; - : bool = false Comparison operators produces boolean values: a = b a <> b a < b a <= b a > b a >= b true if a and b are equal true if a and b are not equal true if a is less than b true if a is less than or equal to b true if a is greater than b true if a is greater than or equal to b Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

7 Boolean Operators Boolean expressions are combined by boolean operators: # true && false;; - : bool = false # true false;; - : bool = true # (2 > 1) && (3 > 2);; - : bool = true Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

8 ML is a Statically Typed Language If you try to evaluate an expression that does not make sense, OCaml rejects and does not evaluate the program: e.g., # 1 + true;; Error: This expression has type bool but an expression was expected of type int Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

9 cf) Static Types and Dynamic Types Programming languages are classified into: Statically typed languages: type checking is done at compile-time. type errors are detected before program executions C, C++, Java, ML, Scala, etc Dynamically typed languages: type checking is done at run-time. type errors are detected during program executions Python, JavaScript, Ruby, Lisp, etc Statically typed languages are further classified into: Type-safe languages guarantee that compiled programs do not have type errors at run-time. All type errors are detected at compile time. Compiled programs do not stuck. ML, Haskell, Scala Unsafe languages do not provide such a guarantee. Some type errors remain at run-time. C, C++ Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

10 Which one is better? Statically typed languages: (+) Type errors are caught early in the development cycle. (+) Program execution is efficient by omitting runtime checks. ( ) Less flexible than dynamic languages. Dynamically typed languages: ( ) Type errors appear at run-time, often unexpectedly. (+) Provide more flexible language features. (+) Easy and fast prototyping. Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

11 Conversion between Different Types In OCaml, different types of values are distinguished: # ;; Error: This expression has type float but an expression was expected of type int Types must be explicitly converted: # 3 + int_of_float 2.0;; - : int = 5 Operators for floating point numbers: # ;; - : float = 3.5 # 1.5 *. 2.0;; - : float = 3. # float_of_int ;; - : float = 3.2 Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

12 Other Primitive Values OCaml provides six primitive values: integers, booleans, floating point numbers, characters, strings, and unit. # c ;; - : char = c # "cose212";; - : string = "cose212" # ();; - : unit = () Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

13 Conditional Expressions if be then e 1 else e 2 If be is true, the value of the conditional expression is the value of e 1. If be is false, the value of the expression is the value of e 2. # if 2 > 1 then 0 else 1;; - : int = 0 # if 2 < 1 then 0 else 1;; - : int = 1 be must be a boolean expression. types of e 1 and e 2 must be equivalent. # if 1 then 1 else 2;; Error:... # if true then 1 else true;; Error:... # if true then true else false;; - : bool = true Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

14 Names and Functions Create a global variable with the let keyword: # let x = 3 + 4;; val x : int = 7 We say a variable x is bound to value 7. # let y = x + x;; val y : int = 14 Create a local variable with let... let x = e 1 in e 2 in... construct: x is bound to the value of e1 the scope of x is e2 the value of e2 becomes the value of the entire expression Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

15 Examples # let a = 1 in a;; - : int = 1 # let a = 1 in a * 2;; - : int = 2 # let a = 1 in let b = a + a in let c = b + b in c + c;; - : int = 8 # let d = let a = 1 in let b = a + a in let c = b + b in c + c;; val d : int = 8 Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

16 Functions Define a function with let: # let square x = x * x;; val square : int -> int = <fun> Apply the function: # square 2;; - : int = 4 # square (2 + 5);; - : int = 49 # square (square 2);; - : int = 16 The body can be any expression: # let neg x = if x < 0 then true else false;; val neg : int -> bool = <fun> # neg 1;; - : bool = false # neg (-1);; - : bool = true Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

17 Functions Functions with multiple arguments: # let sum_of_squares x y = (square x) + (square y);; val sum_of_squares : int -> int -> int = <fun> # sum_of_squares 3 4;; - : int = 25 Recursive functions are defined with let rec construct: # let rec factorial a = if a = 1 then 1 else a * factorial (a - 1);; val factorial : int -> int = <fun> # factorial 5;; - : int = 120 Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

18 Nameless Functions Many modern programming languages provide nameless functions, e.g., ML, Scala, Java8, JavaScript, Python, etc. In OCaml, a function can be defined without names: # fun x -> x * x;; - : int -> int = <fun> Called nameless or anonymous functions. Apply nameless function as usual: # (fun x -> x * x) 2;; - : int = 4 A variable can be bound to functions: # let square = fun x -> x * x;; val square : int -> int = <fun> The followings are equivalent: let square = fun x -> x * x let square x = x * x Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

19 Example: Square Roots with Newton s Method We implement the function sqrt : float > float using Newton s method. To compute sqrt(x), ex) Start with an initial guess y for the value of the square root of x (pick y = 1). Repeatedly improve the estimate by taking the mean of y and x/y. Estimation Quotient Mean 1 2/1 = /1.5 = / = Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

20 Example: Square Roots with Newton s Method let is_good_enough guess x = abs_float (guess *. guess -. x) < let improve guess x = (guess +. x /. guess) /. 2.0 let rec sqrt_iter guess x = if is_good_enough guess x then guess else sqrt_iter (improve guess x) x let sqrt x = sqrt_iter 1.0 x Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

21 Example: Square Roots with Newton s Method # #use "sqrt.ml";; val is_good_enough : float -> float -> bool = <fun> val improve : float -> float -> float = <fun> val sqrt_iter : float -> float -> float = <fun> val sqrt : float -> float = <fun> # sqrt 9.0;; - : float = # sqrt (sqrt sqrt 3.0);; - : float = # sqrt *. sqrt ;; - : float = Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

22 Functions are First-Class in OCaml In programming languages, a value is first-class, if the value can be stored in a variable, passed as an argument of a function, and returned from other functions. A language is often called functional, if functions are first class values, e.g., ML, Scala, Java8, JavaScript, Python, Lisp, etc. Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

23 Functions are First-Class in OCaml Functions can be stored in variables: # let square = fun x -> x * x;; # square 2;; - : int = 4 Functions can be passed to other functions: # let sum_if_true test first second = (if test first then first else 0) + (if test second then second else 0);; val sum_if_true : (int -> bool) -> int -> int -> int = <fun> # let even x = x mod 2 = 0;; val even : int -> bool = <fun> # sum_if_true even 3 4;; - : int = 4 # sum_if_true even 2 4;; - : int = 6 Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

24 Functions are First-Class in OCaml Functions can be also returned from a procedure: # let plus_a a = fun b -> a + b;; val plus_a : int -> int -> int = <fun> # let f = plus_a 3;; val f : int -> int = <fun> # f 1;; - : int = 4 # f 2;; - : int = 5 Functions that manipulate functions are called higher-order functions. i.e., functions that take as argument functions or return functions greatly increase the expressiveness of the language Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

25 Pattern Matching An elegant way of doing case analysis. E.g., using pattern-matching, the factorial function let rec factorial a = if a = 1 then 1 else a * factorial (a - 1) can be written as follows: let factorial a = match a with 1 -> 1 _ -> a * factorial (a - 1) Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

26 Pattern Matching The nested if-then-else expression let isabc c = if c = a then true else if c = b then true else if c = c then true else false can be written using pattern matching: let isabc c = match c with a -> true b -> true c -> true _ -> false or simply, let isabc c = match c with a b c -> true _ -> false Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

27 Type Inference In C or Java, types must be annotated: public static int f(int n) { int a = 2; return a * n; } In OCaml, type annotations are not mandatory: # let f n = let a = 2 in a * n;; val f : int -> int = <fun> Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

28 Type Inference OCaml can infer types, no matter how complex the program is: # let sum_if_true test first second = (if test first then first else 0) + (if test second then second else 0);; val sum_if_true : (int -> bool) -> int -> int -> int = <fun> OCaml compiler infers the type through the following reasoning steps: 1 the types of first and second must be int, because both branches of a conditional expression must have the same type, 2 the type of test is a function type α β, because test is used as a function, 3 α must be of int, because test is applied to first, a value of int, 4 β must be of bool, because conditions must be boolean expressions, 5 the return value of the function has type int, because the two conditional expressions are of int and their addition gives int. Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

29 Type Annotation Explicit type annotations are possible: # let sum_if_true (test : int -> bool) (x : int) (y : int) : int = (if test x then x else 0) + (if test y then y else 0);; val sum_if_true : (int -> bool) -> int -> int -> int = <fun> If the annotation is wrong, OCaml finds the error and report it: # let sum_if_true (test : int -> int) (x : int) (y : int) : int = (if test x then x else 0) + (if test y then y else 0);; Error: The expression (test x) has type int but an expression was expected of type bool Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

30 Polymorphic Types What is the type of the program? let id x = x See how OCaml infers its type: # let id x = x;; val id : a -> a = <fun> The function works for values of any type: # id 1;; - : int = 1 # id "abc";; - : string = "abc" # id true;; - : bool = true Such a function is called polymorphic and a is a type variable. Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

31 Polymorphic Types Quiz) What is the type of the function? let first_if_true test x y = if test x then x else y Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

32 Tuples An ordered collection of values, each of which can be a different types, e.g., # let x = (1, "one");; val x : int * string = (1, "one") # let y = (2, "two", true);; val y : int * string * bool = (2, "two", true) Extract each component using pattern-matching: # let fst p = match p with (x,_) -> x;; val fst : a * b -> a = <fun> # let snd p = match p with (_,x) -> x;; val snd : a * b -> b = <fun> or equivalently, # let fst (x,_) = x;; val fst : a * b -> a = <fun> # let snd (_,x) = x;; val snd : a * b -> b = <fun> Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

33 Tuples Patterns can be used in let: # let p = (1, true);; val p : int * bool = (1, true) # let (x,y) = p;; val x : int = 1 val y : bool = true Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

34 Lists A finite sequence of elements, each of which has the same type, e.g., is a list of integers: [1; 2; 3] # [1; 2; 3];; - : int list = [1; 2; 3] Note that all elements must have the same type, e.g., [1; true; 2] is not a list, the elements are ordered, e.g., [1; 2; 3] [2; 3; 1], and the first element is called head, the rest tail. []: the empty list, i.e., nil. What are head and tail of []? [5]: a list with a single element. What are head and tail of [5]? Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

35 List Examples # [1;2;3;4;5];; - : int list = [1; 2; 3; 4; 5] # ["OCaml"; "Java"; "C"];; - : string list = ["OCaml"; "Java"; "C"] # [(1,"one"); (2,"two"); (3,"three")];; - : (int * string) list = [(1, "one"); (2, "two"); (3, "three")] # [[1;2;3];[2;3;4];[4;5;6]];; - : int list list = [[1; 2; 3]; [2; 3; 4]; [4; 5; 6]] # [1;"OCaml";3] ;; Error: This expression has type string but an expression was expected of type int Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

36 List Operators :: (cons): add a single element to the front of a list, e.g., # 1::[2;3];; - : int list = [1; 2; 3] # 1::2::3::[];; - : int list = [1; 2; 3] ([1; 2; 3] is a shorthand for (append): combine two lists, e.g., # [1; [3; 4; 5];; - : int list = [1; 2; 3; 4; 5] Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

37 Patterns for Lists Pattern matching is useful for manipulating lists. A function to check if a list is empty: # let isnil l = match l with [] -> true _ -> false;; val isnil : a list -> bool = <fun> # isnil [1];; - : bool = false # isnil [];; - : bool = true Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

38 Patterns for Lists A function that computes the length of lists: # let rec length l = match l with [] -> 0 h::t -> 1 + length t;; val length : a list -> int = <fun> # length [1;2;3];; - : int = 3 We can replace pattern h by _: let rec length l = match l with [] -> 0 _::t -> 1 + length t;; Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

39 Data Types If data elements are finite, just enumerate them, e.g., days : # type days = Mon Tue Wed Thu Fri Sat Sun;; type days = Mon Tue Wed Thu Fri Sat Sun Construct values of the type: # Mon;; - : days = Mon # Tue;; - : days = Tue A function that manipulates the defined data: # let nextday d = match d with Mon -> Tue Tue -> Wed Wed -> Thu Thu -> Fri Fri -> Sa Sat -> Sun Sun -> Mon ;; val nextday : days -> days = <fun> # nextday Mon;; - : days = Tue Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

40 Data Types Constructors can be associated with values, e.g., # type shape = Rect of int * int Circle of int;; type shape = Rect of int * int Circle of int Construct values of the type: # Rect (2,3);; - : shape = Rect (2, 3) # Circle 5;; - : shape = Circle 5 A function that manipulates the data: # let area s = match s with Rect (w,h) -> w * h Circle r -> r * r * 3;; val area : shape -> int = <fun> # area (Rect (2,3));; - : int = 6 # area (Circle 5);; - : int = 75 Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

41 Data Types Inductive data types, e.g., # type mylist = Nil List of int * mylist;; type mylist = Nil List of int * mylist Construct values of the type: # Nil;; - : mylist = Nil # List (1, Nil);; - : mylist = List (1, Nil) # List (1, List (2, Nil));; - : mylist = List (1, List (2, Nil)) A function that manipulates the data: # let rec mylength l = match l with Nil -> 0 List (_,l ) -> 1 + mylength l ;; val mylength : mylist -> int = <fun> # mylength (List (1, List (2, Nil)));; - : int = 2 Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

42 Exceptions An exception means a run-time error: e.g., # let div a b = a / b;; val div : int -> int -> int = <fun> # div 10 5;; - : int = 2 # div 10 0;; Exception: Division_by_zero. The exception can be handled with try... # let div a b = try a / b with Division_by_zero -> 0;; val div : int -> int -> int = <fun> # div 10 5;; - : int = 2 # div 10 0;; - : int = 0 with constructs. Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

43 Exceptions User-defined exceptions: e.g., # exception Problem;; exception Problem # let div a b = if b = 0 then raise Problem else a / b;; val div : int -> int -> int = <fun> # div 10 5;; - : int = 2 # div 10 0;; Exception: Problem. # try div 10 0 with Problem -> 0;; - : int = 0 Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

44 Summary We ve gone through the basics of OCaml programming: Expressions Names Functions Pattern matching Type inference Tuples and lists Data types Exceptions Hakjoo Oh COSE Fall, Lecture 3 September 18, / 44

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

COSE212: Programming Languages Lecture 4 Recursive and Higher-Order Programming Hakjoo Oh 2016 Fall Hakjoo Oh COSE212 2016 Fall, Lecture 4 September 27, 2016 1 / 21 Recursive and Higher-Order Programming

### Homework 3 COSE212, Fall 2018

Homework 3 COSE212, Fall 2018 Hakjoo Oh Due: 10/28, 24:00 Problem 1 (100pts) Let us design and implement a programming language called ML. ML is a small yet Turing-complete functional language that supports

### 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 The ML Programming Language General purpose programming language designed by Robin Milner in 1970 Meta Language

### CS558 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

### CS558 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

### CS558 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

### CSCI-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

### 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 The ML Programming Language General purpose programming language designed by Robin Milner in 1970 Meta Language

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

CMSC 330: Organization of Programming Languages Functional Programming with Lists CMSC330 Spring 2018 1 Lists in OCaml The basic data structure in OCaml Lists can be of arbitrary length Implemented as

### 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 Typed Lambda Calculus Chapter 9 Benjamin Pierce Types and Programming Languages Call-by-value Operational Semantics

### CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC330 Fall 2017 OCaml Data Types CMSC330 Fall 2017 1 OCaml Data So far, we ve seen the following kinds of data Basic types (int, float, char, string) Lists

### Lecture: Functional Programming

Lecture: Functional Programming This course is an introduction to the mathematical foundations of programming languages and the implementation of programming languages and language-based tools. We use

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

Announcements n Rainbow grades: HW1-6, Quiz1-5, Exam1 n Still grading: HW7, Quiz6, Exam2 Intro to Haskell n HW8 due today n HW9, Haskell, out tonight, due Nov. 16 th n Individual assignment n Start early!

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

A Fourth Look At ML Chapter Eleven Modern Programming Languages, 2nd ed. 1 Type Definitions Predefined, but not primitive in ML: datatype bool = true false; Type constructor for lists: datatype 'element

Overloading, Type Classes, and Algebraic Datatypes Delivered by Michael Pellauer Arvind Computer Science and Artificial Intelligence Laboratory M.I.T. September 28, 2006 September 28, 2006 http://www.csg.csail.mit.edu/6.827

### CVO103: Programming Languages. Lecture 5 Design and Implementation of PLs (1) Expressions

CVO103: Programming Languages Lecture 5 Design and Implementation of PLs (1) Expressions Hakjoo Oh 2018 Spring Hakjoo Oh CVO103 2018 Spring, Lecture 5 April 3, 2018 1 / 23 Plan Part 1 (Preliminaries):

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

CMSC 330: Organization of Programming Languages OCaml Expressions and Functions CMSC330 Spring 2018 1 Lecture Presentation Style Our focus: semantics and idioms for OCaml Semantics is what the language

### CS 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

### Topic 7: Algebraic Data Types

Topic 7: Algebraic Data Types 1 Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 5.5, 5.7, 5.8, 5.10, 5.11, 5.12, 5.14 14.4, 14.5, 14.6 14.9, 14.11,

### CSCE 314 Programming Languages

CSCE 314 Programming Languages Haskell: Declaring Types and Classes Dr. Hyunyoung Lee 1 Outline Declaring Data Types Class and Instance Declarations 2 Defining New Types Three constructs for defining types:

### Programming Languages Fall 2013

Programming Languages Fall 2013 Lecture 2: types Prof. Liang Huang huang@qc.cs.cuny.edu Recap of Lecture 1 functional programming vs. imperative programming basic Haskell syntax function definition lazy

### CMSC 330: Organization of Programming Languages. OCaml Data Types

CMSC 330: Organization of Programming Languages OCaml Data Types CMSC330 Spring 2018 1 OCaml Data So far, we ve seen the following kinds of data Basic types (int, float, char, string) Lists Ø One kind

### According 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

### Software System Design and Implementation

Software System Design and Implementation Functional Programming Gabriele Keller The University of New South Wales School of Computer Science and Engineering Sydney, Australia COMP3141 16s1 Course software

### Functional Programming. Pure Functional Programming

Functional Programming With examples in F# Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands. Computation is largely performed by applying

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

CMSC 330: Organization of Programming Languages Functional Programming with Lists 1 Lists in OCaml The basic data structure in OCaml Lists can be of arbitrary length Implemented as a linked data structure

### Chapter 15. Functional Programming. Topics. Currying. Currying: example. Currying: example. Reduction

Topics Chapter 15 Functional Programming Reduction and Currying Recursive definitions Local definitions Type Systems Strict typing Polymorphism Classes Booleans Characters Enumerations Tuples Strings 2

### Lists. 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

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

Motivation Introduction to Objective Caml Why OCaml? Stefan Wehr University of Freiburg. October 30, 2006 Motivation Simple Expressions and Types I/O and Compilation Resources Convenient encoding of tree

### Functional Programming. Lecture 2: Algebra

Functional Programming by Łukasz Stafiniak Email: lukstafi@gmail.com, lukstafi@ii.uni.wroc.pl Web: www.ii.uni.wroc.pl/~lukstafi Lecture 2: Algebra Algebraic Data Types and some curious analogies 1 A Glimpse

### Introduction to Objective Caml

Introduction to Objective Caml Stefan Wehr University of Freiburg. October 30, 2006 Motivation Simple Expressions and Types Functions Simple Pattern Matching Compound Datatypes I/O and Compilation Resources

### CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages Type Systems, Names and Binding CMSC 330 - Spring 2013 1 Topics Covered Thus Far! Programming languages Ruby OCaml! Syntax specification Regular expressions

### OCaml 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

### Data Types The ML Type System

7 Data Types 7.2.4 The ML Type System The following is an ML version of the tail-recursive Fibonacci function introduced Fibonacci function in ML in Section 6.6.1: EXAMPLE 7.96 1. fun fib (n) = 2. let

### CSE 3302 Programming Languages Lecture 8: Functional Programming

CSE 3302 Programming Languages Lecture 8: Functional Programming (based on the slides by Tim Sheard) Leonidas Fegaras University of Texas at Arlington CSE 3302 L8 Spring 2011 1 Functional Programming Languages

### Type 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

### Introduction 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

### Haskell 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

### G Programming Languages - Fall 2012

G22.2110-003 Programming Languages - Fall 2012 Lecture 3 Thomas Wies New York University Review Last week Names and Bindings Lifetimes and Allocation Garbage Collection Scope Outline Control Flow Sequencing

### Lecture 12: Data Types (and Some Leftover ML)

Lecture 12: Data Types (and Some Leftover ML) COMP 524 Programming Language Concepts Stephen Olivier March 3, 2009 Based on slides by A. Block, notes by N. Fisher, F. Hernandez-Campos, and D. Stotts Goals

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

Closures Mooly Sagiv Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming Summary 1. Predictive Parsing 2. Large Step Operational Semantics (Natural) 3. Small Step Operational Semantics

### Lecture #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:

### Introduction to Functional Programming

Introduction to Functional Programming Xiao Jia xjia@cs.sjtu.edu.cn Summer 2013 Scheme Appeared in 1975 Designed by Guy L. Steele Gerald Jay Sussman Influenced by Lisp, ALGOL Influenced Common Lisp, Haskell,

### CS558 Programming Languages

CS558 Programming Languages Fall 2016 Lecture 7a Andrew Tolmach Portland State University 1994-2016 Values and Types We divide the universe of values according to types A type is a set of values and a

### Conversion 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";

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

CSC312 Principles of Programming Languages : Functional Programming Language Overview of Functional Languages They emerged in the 1960 s with Lisp Functional programming mirrors mathematical functions:

### A 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

### OCaml. 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

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

Chapter 14 Functional Programming Programming Languages 2nd edition Tucker and Noonan It is better to have 100 functions operate one one data structure, than 10 functions on 10 data structures. A. Perlis

### Programming 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

### Plan (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

### CS 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

### Lecture #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 ::

### CSE 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

### Mini-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

### COP4020 Programming Assignment 1 - Spring 2011

COP4020 Programming Assignment 1 - Spring 2011 In this programming assignment we design and implement a small imperative programming language Micro-PL. To execute Mirco-PL code we translate the code to

### Programming Languages Lecture 14: Sum, Product, Recursive Types

CSE 230: Winter 200 Principles of Programming Languages Lecture 4: Sum, Product, Recursive Types The end is nigh HW 3 No HW 4 (= Final) Project (Meeting + Talk) Ranjit Jhala UC San Diego Recap Goal: Relate

### CSE 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

### CMSC 330, Fall 2013, Practice Problems 3

CMSC 330, Fall 2013, Practice Problems 3 1. OCaml and Functional Programming a. Define functional programming b. Define imperative programming c. Define higher-order functions d. Describe the relationship

### PROGRAMMING IN HASKELL. Chapter 2 - First Steps

PROGRAMMING IN HASKELL Chapter 2 - First Steps 0 The Hugs System Hugs is an implementation of Haskell 98, and is the most widely used Haskell system; The interactive nature of Hugs makes it well suited

### So 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

### Programming in Haskell Aug-Nov 2015

Programming in Haskell Aug-Nov 2015 LECTURE 14 OCTOBER 1, 2015 S P SURESH CHENNAI MATHEMATICAL INSTITUTE Enumerated data types The data keyword is used to define new types data Bool = False True data Day

### SML 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

### OCaml. 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

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

CMSC 330: Organization of Programming Languages OCaml 1 Functional Programming Dialects of ML ML (Meta Language) Univ. of Edinburgh,1973 Part of a theorem proving system LCF The Logic of Computable Functions

### COSE212: Programming Languages. Lecture 0 Course Overview

COSE212: Programming Languages Lecture 0 Course Overview Hakjoo Oh 2017 Fall Hakjoo Oh COSE212 2017 Fall, Lecture 0 September 4, 2017 1 / 9 Basic nformation nstructor: Hakjoo Oh TAs: Position: Assistant

### Lecture 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

### CMSC 330: Organization of Programming Languages. Rust Basics

CMSC 330: Organization of Programming Languages Rust Basics CMSC330 Spring 2018 1 Organization It turns out that a lot of Rust has direct analogues in OCaml So we will introduce its elements with comparisons

### Chapter 1. Fundamentals of Higher Order Programming

Chapter 1 Fundamentals of Higher Order Programming 1 The Elements of Programming Any powerful language features: so does Scheme primitive data procedures combinations abstraction We will see that Scheme

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

CSE 130 : Fall 2007 Programming Languages News PA deadlines shifted PA #2 now due 10/24 (next Wed) Lecture 5: Functions and Datatypes Ranjit Jhala UC San Diego Recap: Environments Phone book Variables

### News. 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

Functional Programming and Haskell Tim Dawborn University of Sydney, Australia School of Information Technologies Tim Dawborn Functional Programming and Haskell 1/22 What are Programming Paradigms? A programming

### Case by Case. Chapter 3

Chapter 3 Case by Case In the previous chapter, we used the conditional expression if... then... else to define functions whose results depend on their arguments. For some of them we had to nest the conditional

### Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

CMSC 330: Organization of Programming Languages Tail Calls A tail call is a function call that is the last thing a function does before it returns let add x y = x + y let f z = add z z (* tail call *)

### Programming 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

### Recap 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

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

A Third Look At ML Chapter Nine Modern Programming Languages, 2nd ed. 1 Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order

### CS 11 Haskell track: lecture 1

CS 11 Haskell track: lecture 1 This week: Introduction/motivation/pep talk Basics of Haskell Prerequisite Knowledge of basic functional programming e.g. Scheme, Ocaml, Erlang CS 1, CS 4 "permission of

### More Lambda Calculus and Intro to Type Systems

More Lambda Calculus and Intro to Type Systems Plan Heavy Class Participation Thus, wake up! Lambda Calculus How is it related to real life? Encodings Fixed points Type Systems Overview Static, Dyamic

### Topics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited

CMSC 330: Organization of Programming Languages Type Systems, Names & Binding Topics Covered Thus Far Programming languages Syntax specification Regular expressions Context free grammars Implementation

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

Closures Mooly Sagiv Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming t ::= x x. t t t Call-by-value big-step Operational Semantics terms variable v ::= values abstraction x.

### CSc 372. Comparative Programming Languages. 4 : Haskell Basics. Department of Computer Science University of Arizona

1/40 CSc 372 Comparative Programming Languages 4 : Haskell Basics Department of Computer Science University of Arizona collberg@gmail.com Copyright c 2013 Christian Collberg 2/40 The Hugs Interpreter The

### CPS 506 Comparative Programming Languages. Programming Language Paradigm

CPS 506 Comparative Programming Languages Functional Programming Language Paradigm Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages The First Functional Programming

### CSc 372 Comparative Programming Languages. 4 : Haskell Basics

CSc 372 Comparative Programming Languages 4 : Haskell Basics Christian Collberg Department of Computer Science University of Arizona collberg@gmail.com Copyright c 2011 Christian Collberg August 23, 2011

### ITT8060: Advanced Programming (in F#)

based on slides by Michael R. Hansen ITT8060: Advanced Programming (in F#) Lecture 2: Identifiers, values, expressions, functions and types Juhan Ernits Department of Software Science, Tallinn University

### Typed 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

### Whereweare. CS-XXX: Graduate Programming Languages. Lecture 7 Lambda Calculus. Adding data structures. Data + Code. What about functions

Whereweare CS-XXX: Graduate Programming Languages Lecture 7 Lambda Calculus Done: Syntax, semantics, and equivalence For a language with little more than loops and global variables Now: Didn t IMP leave

### Programming 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

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

Lists Adrian Groza Department of Computer Science Technical University of Cluj-Napoca Recall... Parameter evaluation Call-by-value Call-by-name Call-by-need Functions Infix operators Local declarations,

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

CS 490.40 Lectures 2-3 Introduction to OCaml Polyvios Pratikakis Based on slides by Jeff Foster History ML: Meta Language 1973, University of Edinburg Used to program search tactics in LCF theorem prover

### Types, Type Inference and Unification

Types, Type Inference and Unification Mooly Sagiv Slides by Kathleen Fisher and John Mitchell Cornell CS 6110 Summary (Functional Programming) Lambda Calculus Basic ML Advanced ML: Modules, References,

### COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

COP4020 Programming Languages Functional Programming Prof. Robert van Engelen Overview What is functional programming? Historical origins of functional programming Functional programming today Concepts

### CMSC 330, Fall 2013, Practice Problem 3 Solutions

CMSC 330, Fall 2013, Practice Problem 3 Solutions 1. OCaml and Functional Programming a. Define functional programming Programs are expression evaluations b. Define imperative programming Programs change

### CSCE 314 Programming Languages

CSCE 314 Programming Languages Final Review Part I Dr. Hyunyoung Lee 1 Programming Language Characteristics Different approaches to describe computations, to instruct computing devices E.g., Imperative,

### Programming Paradigms and Languages Introduction to Haskell. dr Robert Kowalczyk WMiI UŁ

Programming Paradigms and Languages Introduction to Haskell dr Robert Kowalczyk WMiI UŁ Functional programming In functional programming (special type of declarative programming), programs are executed

### LECTURE 16. Functional Programming

LECTURE 16 Functional Programming WHAT IS FUNCTIONAL PROGRAMMING? Functional programming defines the outputs of a program as a mathematical function of the inputs. Functional programming is a declarative

### Introduction to OCaml

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

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

Announcements CSCI 334: Principles of Programming Languages Lecture 5: Fundamentals III & ML Instructor: Dan Barowy Claire Booth Luce info session tonight for women interested in summer research (hopefully