Fall Lecture 13 Thursday, October 11

Size: px
Start display at page:

Download "Fall Lecture 13 Thursday, October 11"

Transcription

1 Fall 2018 Lecture 13 Thursday, October 11

2 n queens One s favorite ipod app

3 n queens Queens attack on row, column, or diagonal Task: put n queens safely on an n-by-n board

4 British Museum algorithm Definition: A general approach that finds a solution by checking all possibilities one by one. Not a practical technique when the number of possibilities is enormous.

5 before we start Number of ways to put 8 queens on board 64! 58! 8! 4,000,000,000

6 before we start Number of ways to put 8 queens on board 4,000,000,000 Number of ways using different columns 8! 40,000

7 before we start Number of ways to put 8 queens on board 4,000,000,000 Number of ways using different columns 40,000 Number of safe ways 92

8 before we start Number of ways to put 8 queens on board 4,000,000,000 Number of ways using different columns 40,000 Number of safe ways 92 How many solutions do we want? 1

9 a fast algorithm? PRICELESS ML Card there are some things money can t buy; for everything else there s ML

10 backtracking Many search algorithms backtrack from a dead end, to an earlier choice point, in order to explore further alternatives Easy to implement with a failure continuation

11 classic n-queens Try placing a queen in each row Check for attacks by queens in previous rows If SAFE, start on next row. If UNSAFE and reached end of row, BACKTRACK

12 col 1 col 2 col 3 col 4 row 4 starting 4-by-4 algorithm row 3 no queens yet row 2 trying row 1, col 1 row 1? SAFE

13 col 1 col 2 col 3 col 4 row 4 row 3 row 2? trying row 2, col 1 row 1? queen at (1,1) SAFE

14 col 1 col 2 col 3 col 4 row 4 row 3 row 2 row 1, col 1 UNSAFE row 1 queen at (1,1) SAFE

15 row 4 row 3 row 2 row 2, col 1 UNSAFE row 1? col 1 col 2 col 3 col 4 queen at (1,1) SAFE

16 col 1 col 2 col 3 col 4 row 4 row 3 row 2 row 2, col 3 SAFE row 1? queen at (1,1) SAFE

17 trying row 3, col 1 queens at (1,1), (2,3) SAFE

18 trying row 3, col 1 queens at (1,1), (2,3) SAFE

19 trying row 3, col 1 queens at (1,1), (2,3) SAFE

20 trying row 3, col 2 queens at (1,1), (2,3) SAFE

21 trying row 3, col 2 queens at (1,1), (2,3) SAFE

22 trying row 3, col 2 queens at (1,1), (2,3) SAFE

23 trying row 3, col 3 queens at (1,1), (2,3) SAFE

24 trying row 3, col 3 queens at (1,1), (2,3) SAFE

25 trying row 3, col 3 queens at (1,1), (2,3) SAFE

26 trying row 3, col 4 queens at (1,1), (2,3) SAFE

27 trying row 3, col 4 queens at (1,1), (2,3) SAFE

28 trying row 3, col 4 queens at (1,1), (2,3) SAFE

29 with queens at (1,1), (2,3) trying row 3, col 4 there s no safe place in row 3 queens at (1,1), (2,3) SAFE

30 with queens at (1,1), (2,3) trying row 3, col 4 there s no safe place in row 3 so backtrack queens at (1,1), (2,3) SAFE

31 ? backtrack to

32 ? backtrack to

33 backtrack to? queens at (1,1), (2,4)

34 backtrack to? queens at (1,1), (2,4) SAFE

35 backtrack to? trying row 3, col 1 queens at (1,1), (2,4) SAFE

36 backtrack to? trying row 3, col 1 queens at (1,1), (2,4) SAFE

37

38

39 safe so far, but what next?

40 at end of algorithm queens at (1,3), (2,1), (3,4), (4,2) safe!

41 algorithm ideas Start with no queens on the board At each stage we have a partial solution Try to extend partial solution with a queen in the next row If not possible, backtrack and adjust the partial solution

42 board type row = int type col = int type pos = row * col type sol = pos list

43 threat threat : pos * pos -> bool fun threat((x,y), (i,j)) = (x=i) orelse (y=j) orelse (x+y = i+j) orelse (x-y = i-j) threat(p, q) = true iff p attacks q

44 conflict conflict : pos * pos list -> bool fun conflict (p, nil) = false conflict (p, q::qs) = threat(p, q) orelse conflict(p, qs) conflict (p, [q1,...,qk]) = false if threat(p, qi) = false for each i conflict (p, [q1,...,qk]) = true if threat(p, qi) = true for some i q2 q4 q1 q5 q

45 safe safe : pos list -> bool fun safe [ ] = true safe (q::qs) = if conflict(q, qs) then false else safe(qs) safe [q1,...,qk] = true iff for all i j, qi and qj are on different rows, columns and diagonals

46 solutions qs is a partial solution for rows 1 through i if safe qs & map (fn (x, y) => x) qs = [i,..., 1] & map (fn (x, y) => y) qs is a subset of {1,,n} A full solution to the n-queens problem is a partial solution for rows 1 through n

47 failure continuations Many search algorithms can be solved elegantly using partial solutions and failure continuations The continuation says what to do if we reach a dead end There s no need to propagate a partial solution (it was a dead end!) So a failure continuation will be a function with a dummy argument ( ) : unit

48 answers type ans = sol option SOME qs NONE means found the solution qs means no solution exists continuations type cont = unit -> ans

49 strategy A recursive function that maintains a partial solution and tries to extend it by adding a queen in the next row Its arguments should indicate the board size the current partial solution the next row the columns still to be tried, in the next row what to do if we reach a dead end

50 try try : int * row * col list * sol -> (unit -> sol option) -> sol option try(n, i, A, qs) fc REQUIRES: 1 i n and A is a sublist of [1,...,n] & qs is a partial solution for rows 1 through i-1 ENSURES: EITHER try (n, i, A, qs) fc = SOME(qs ) where qs is a full solution extending qs with a queen in row i at a column in A OR try (n, i, A, qs) fc = fc( ) & there is no solution extending qs with a queen in row i at a column in A

51 try try : int * row * col list * sol -> (unit -> sol option) -> sol option try(n, i, A, qs) fc REQUIRES: 1 i n and A is a sublist of [1,...,n] & qs is a partial solution for rows 1 through i-1 ENSURES: (1) try (n, i, A, qs) fc = SOME(qs ) where qs is a full solution extending qs with a queen in row i at a column in A, if there is one (2) try (n, i, A, qs) fc = fc( ) otherwise (if there s no such solution)

52 try(n, i, A, qs) fc columns to be tried for row i partial solution on rows 1...i-1 If A = [ ], there is no solution extending qs, so fail If A = j::b, either (i,j) is attacked by qs, so try columns from B for row i or it s safe to extend qs with (i,j); if i=n, (i,j)::qs is a full solution; otherwise, look for a solution extending (i,j)::qs in row i+1, and if this fails, backtrack to try columns from B for row i.

53 try(n, i, A, qs) fc columns to be tried for row i partial solution on rows 1...i-1 If A = [ ], there is no solution extending qs, so fail fc( ) conflict((i,j), qs)=true If A = j::b, try(n, i, B, qs) fc either (i,j) is attacked by qs, so try columns from B for row i or it s safe to extend qs with (i,j); if i=n, (i,j)::qs is a full solution; otherwise, look for a solution extending (i,j)::qs in row i+1, and if this fails, backtrack to try columns from B for row i. conflict((i,j), qs)=false try(n, i+1, [1,...,n], (i,j)::qs) (fn ( ) => try(n, i, B, qs) fc)

54 try fun try (n, i, A, qs) fc = case A of [ ] => fc( ) j::b => if conflict((i, j), qs) then try (n, i, B, qs) fc else if i = n then SOME( (i, j)::qs ) else try(n, i+1, upto 1 n, (i, j)::qs) (fn ( ) => try (n, i, B, qs) fc)

55 queens queens : int -> sol option REQUIRES: n > 0 ENSURES: (1) queens n = SOME qs where qs is an n-queens solution, if there is one; (2) queens n = NONE otherwise

56 queens queens : int -> sol option REQUIRES: n > 0 ENSURES: EITHER queens n = SOME qs where qs is an n-queens solution; OR queens n = NONE & there is no n-queens solution.

57 queens Look for solution extending [ ] with a queen in row 1 fun queens n = try (n, 1, upto 1 n, nil) (fn ( ) => NONE) Pessimistic failure continuation

58 results queens 3 = NONE queens 4 = SOME [(4,3),(3,1),(2,4),(1,2)] queens 5 = SOME [(5,4),(4,2),(3,5),(2,3),(1,1)] queens 8 = SOME [(8,4),(7,2),(6,7),(5,3),(4,6),(3,8),(2,5),(1,1)] queens 20 = SOME [(20,11),(19,6),(18,14),(17,7),(16,10),...]

59 queens 4 = SOME [(4,3),(3,1),(2,4),(1,2)]

60 8-queens Q Q Q Q Q Q Q Q

61 correctness? For all total fc, and all (n, i, A, qs) such that 1 i n, A is a sublist of [1,...,n] & qs is a partial solution on rows 1 through i-1, EITHER try (n, i, A, qs) fc = SOME(qs ) where qs is a full solution extending qs with a queen in row i at a column in A OR try (n, i, A, qs) fc = fc( ) & there is no full solution extending qs with a queen in row i at a column in A.

62 proof idea Assuming REQUIRES property, in each recursive call either the row index i stays the same and the length of the column list A decreases, or the row index i increases The row index is always between 1 and n So (n - i, length A) decreases lexicographically (x1, y1) > (x2, y2) if x1>x2 or (x1=x2 and y1 > y2) Use induction on (n-i, length A)

63 direct-style A function of type t 1 -> t 2 can be applied to an argument of type t 1, and returns a value of type t 2. A direct-style function evaluates its argument, returns a result.

64 continuation-style A continuation-style function of type t1 -> (t2 -> a) -> a can be applied to an argument of type t1 and a continuation of type t2 -> a, where a is a type of answers. Instead of returning, it passes a value to its continuation, to get an answer.

65 continuation? A function that represents the rest of a computation or what to do next Expects to be called with a value ( the result so far ) and computes a final value (an answer )

66 direct cps Every direct-style function definition can be turned into a cps function definition a purely syntactic transformation The cps version makes control flow and intermediate values explicit The cps version is also tail recursive

67 factorial (* fact : int -> int *) fun fact n = if n=0 then 1 else n * fact(n-1) direct style not tail recursive (* fact : int -> (int -> a) -> a *) fun fact n k = continuation style if n=0 then k 1 else fact (n-1)(fn x => k(n * x)) tail recursive

68 examples fact 3 (fn x => x) = 6 fact 3 Int.toString = 6 fact 3 (fn y -> fact y Int.toString) =?

69 specs fact : int -> int REQUIRES n 0 ENSURES fact(n) = n! fact : int -> (int -> a) -> a REQUIRES n 0 ENSURES fact n k = k(n!)

70 proof Let ans be a type, and let P(n) be: For all k : int -> ans, fact n k = k(fact n) Prove n 0. P(n) Use induction on n fact 3 (fn m => m+1) = 7

71 polymorphic The cps factorial has a polymorphic type int -> (int -> a) -> a Why? Because it does the same thing no matter what the continuation is (passes a value to the continuation) (and that value doesn t dependent on the continuation) (and the cps factorial doesn t care what the continuation does)

72 cps When applied, a cps function calls its continuation at most once Passes the same value, regardless of the continuation Has the same control flow as direct-style fun fact n = if n=0 then 1 else n * fact(n-1) fun fact n k = if n=0 then k 1 else fact (n-1)(fn x => k(n*x))

73 not cps fun fact n k = if n=0 then k 1 else n * fact (n-1) k fact : int -> (int -> int) -> int fact 3 (fn m => m+1) = 12 according to spec, should evaluate to 7

74 not cps fun fact n k = if n=0 then 1 else fact (n-1) (fn x => k(x*n)) fact : int -> (int -> int) -> int fact 3 (fn m => m+1) = 1 according to spec, should evaluate to 7

75 counting a tree count : int tree -> int count : int tree -> (int -> a) -> a fun count Empty = 0 count (Node(A,x,B)) = count A + x + count B fun count Empty k = k 0 count (Node(A, x, B)) k = count A (fn m => count B (fn n => k(m+x+n))

76 not cps fun count Empty k = k 0 count (Node(A, x, B)) k = count A k + x + count B k Why not? What s its type? What goes wrong?

77 tail recursion A recursive function definition is tail recursive if each recursive call is in tail position, the last thing the function does before returning. fun fact n = if n=0 then 1 else n * fact(n-1) fun factacc(n, a) = if n=0 then a else factacc(n-1, n*a) fun fact n k = if n=0 then k 1 else fact (n-1) (fn x => k(n * x))

78 tail call elimination Tail calls can be implemented in a space-efficient manner. When a function is called, the argument values get pushed onto a stack, with a return address for the value returned by the call. For tail calls, we can re-use the same stack frame for arguments and leave the return address unchanged: the result of the tail call needs to get returned to the original call site. Execution of factacc(3, 1) call factacc (3, 1) call factacc (2, 3) call factacc (1, 6) call factacc (0, 6) return 6 return 6 return 6 return 6 With tail call elimination call factacc (3, 1) replace args with (2, 3) replace args with (1, 6) replace args with (0, 6) return 6

Australian researchers develop typeface they say can boost memory, that could help students cramming for exams.

Australian researchers develop typeface they say can boost memory, that could help students cramming for exams. Font of all knowledge? Australian researchers develop typeface they say can boost memory, that could help students cramming for exams. About 400 university students took part in a study that found a small

More information

CSE 341 : Programming Languages Midterm, Spring 2015

CSE 341 : Programming Languages Midterm, Spring 2015 Name: CSE 341 : Programming Languages Midterm, Spring 2015 Please do not turn the page until 12:30. Rules: Closed book, closed note, except for one side of one 8.5x11in piece of paper. Please stop promptly

More information

CS200: Recursion and induction (recap from cs161)

CS200: Recursion and induction (recap from cs161) CS200: Recursion and induction (recap from cs161) Prichard Ch. 6.1 & 6.3 1 2 Backtracking n Problem solving technique that involves moves: guesses at a solution. n Depth First Search: in case of failure

More information

CSE341, Fall 2011, Midterm Examination October 31, 2011

CSE341, 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 information

Recursive Search with Backtracking

Recursive Search with Backtracking CS 311 Data Structures and Algorithms Lecture Slides Friday, October 2, 2009 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks CHAPPELLG@member.ams.org 2005 2009 Glenn G.

More information

Fall Lecture 3 September 4. Stephen Brookes

Fall 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 information

CSE341, Fall 2011, Midterm Examination October 31, 2011

CSE341, 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 information

Lecture Notes on Induction and Recursion

Lecture Notes on Induction and Recursion Lecture Notes on Induction and Recursion 15-317: Constructive Logic Frank Pfenning Lecture 7 September 19, 2017 1 Introduction At this point in the course we have developed a good formal understanding

More information

Fall Recursion and induction. Stephen Brookes. Lecture 4

Fall Recursion and induction. Stephen Brookes. Lecture 4 15-150 Fall 2018 Stephen Brookes Lecture 4 Recursion and induction Last time Specification format for a function F type assumption guarantee (REQUIRES) (ENSURES) For all (properly typed) x satisfying the

More information

APCS-AB: Java. Recursion in Java December 12, week14 1

APCS-AB: Java. Recursion in Java December 12, week14 1 APCS-AB: Java Recursion in Java December 12, 2005 week14 1 Check point Double Linked List - extra project grade Must turn in today MBCS - Chapter 1 Installation Exercises Analysis Questions week14 2 Scheme

More information

15 212: Principles of Programming. Some Notes on Continuations

15 212: Principles of Programming. Some Notes on Continuations 15 212: Principles of Programming Some Notes on Continuations Michael Erdmann Spring 2011 These notes provide a brief introduction to continuations as a programming technique. Continuations have a rich

More information

CMSC 132: Object-Oriented Programming II. Recursive Algorithms. Department of Computer Science University of Maryland, College Park

CMSC 132: Object-Oriented Programming II. Recursive Algorithms. Department of Computer Science University of Maryland, College Park CMSC 132: Object-Oriented Programming II Recursive Algorithms Department of Computer Science University of Maryland, College Park Recursion Recursion is a strategy for solving problems A procedure that

More information

A Concepts-Focused Introduction to Functional Programming Using Standard ML Sample Exam #1 Draft of August 12, 2010

A Concepts-Focused Introduction to Functional Programming Using Standard ML Sample Exam #1 Draft of August 12, 2010 A Concepts-Focused Introduction to Functional Programming Using Standard ML Sample Exam #1 Draft of August 12, 2010 Rules: The exam is closed-book, closed-note, except for one side of one 8.5x11in piece

More information

Lecture 6: Recursion RECURSION

Lecture 6: Recursion RECURSION Lecture 6: Recursion RECURSION You are now Java experts! 2 This was almost all the Java that we will teach you in this course Will see a few last things in the remainder of class Now will begin focusing

More information

Continuation Passing Style. Continuation Passing Style

Continuation Passing Style. Continuation Passing Style 161 162 Agenda functional programming recap problem: regular expression matcher continuation passing style (CPS) movie regular expression matcher based on CPS correctness proof, verification change of

More information

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

Redefinition of an identifier is OK, but this is redefinition not assignment; Thus Redefinition of an identifier is OK, but this is redefinition not assignment; Thus val x = 100; val x = (x=100); is fine; there is no type error even though the first x is an integer and then it is a boolean.

More information

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

COSE212: 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 information

Lecture 6: Sequential Sorting

Lecture 6: Sequential Sorting 15-150 Lecture 6: Sequential Sorting Lecture by Dan Licata February 2, 2012 Today s lecture is about sorting. Along the way, we ll learn about divide and conquer algorithms, the tree method, and complete

More information

F28PL1 Programming Languages. Lecture 14: Standard ML 4

F28PL1 Programming Languages. Lecture 14: Standard ML 4 F28PL1 Programming Languages Lecture 14: Standard ML 4 Polymorphic list operations length of list base case: [] ==> 0 recursion case: (h::t) => 1 more than length of t - fun length [] = 0 length (_::t)

More information

Continuations and Continuation-Passing Style

Continuations and Continuation-Passing Style Continuations and Continuation-Passing Style Lecture 4 CS 390 1/16/08 Goal Weʼre interested in understanding how to represent the state of a co-routine Insight into what a thread really means How fundamental

More information

CSE 341 Section 5. Winter 2018

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

More information

CSE3322 Programming Languages and Implementation

CSE3322 Programming Languages and Implementation Monash University School of Computer Science & Software Engineering Sample Exam 2004 CSE3322 Programming Languages and Implementation Total Time Allowed: 3 Hours 1. Reading time is of 10 minutes duration.

More information

Mini-ML. CS 502 Lecture 2 8/28/08

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

More information

Chapter 3 Linear Structures: Lists

Chapter 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 information

CS558 Programming Languages

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

More information

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 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 information

Practice Problems for the Final

Practice Problems for the Final ECE-250 Algorithms and Data Structures (Winter 2012) Practice Problems for the Final Disclaimer: Please do keep in mind that this problem set does not reflect the exact topics or the fractions of each

More information

Fall Lecture 8 Stephen Brookes

Fall Lecture 8 Stephen Brookes 15-150 Fall 2018 Lecture 8 Stephen Brookes trees vs. lists Representing a collection as a (balanced) tree instead of a list may yield a parallel speed-up Using a sorted (balanced) tree may even yield faster

More information

CS153: Compilers Lecture 15: Local Optimization

CS153: Compilers Lecture 15: Local Optimization CS153: Compilers Lecture 15: Local Optimization Stephen Chong https://www.seas.harvard.edu/courses/cs153 Announcements Project 4 out Due Thursday Oct 25 (2 days) Project 5 out Due Tuesday Nov 13 (21 days)

More information

Chapter 3 Linear Structures: Lists

Chapter 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 information

COT 3100 Spring 2010 Midterm 2

COT 3100 Spring 2010 Midterm 2 COT 3100 Spring 2010 Midterm 2 For the first two questions #1 and #2, do ONLY ONE of them. If you do both, only question #1 will be graded. 1. (20 pts) Give iterative and recursive algorithms for finding

More information

Programming Languages Lecture 14: Sum, Product, Recursive Types

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

More information

Functional programming Primer I

Functional 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 information

EECS 477: Introduction to algorithms. Lecture 7

EECS 477: Introduction to algorithms. Lecture 7 EECS 477: Introduction to algorithms. Lecture 7 Prof. Igor Guskov guskov@eecs.umich.edu September 26, 2002 1 Lecture outline Recursion issues Recurrence relations Examples 2 Recursion: factorial unsigned

More information

8/22/12. Outline. Backtracking. The Eight Queens Problem. Backtracking. Part 1. Recursion as a Problem-Solving Technique

8/22/12. Outline. Backtracking. The Eight Queens Problem. Backtracking. Part 1. Recursion as a Problem-Solving Technique Part 1. Recursion as a Problem-Solving Technique CS 200 Algorithms and Data Structures CS 200 Algorithms and Data Structures [Fall 2011] 2 Outline Backtracking Formal grammars Relationship between recursion

More information

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Fall 2011

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Fall 2011 CSE341: Programming Languages Lecture 9 Function-Closure Idioms Dan Grossman Fall 2011 More idioms We know the rule for lexical scope and function closures Now what is it good for A partial but wide-ranging

More information

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

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013 CSE341: Programming Languages Lecture 9 Function-Closure Idioms Dan Grossman Winter 2013 More idioms We know the rule for lexical scope and function closures Now what is it good for A partial but wide-ranging

More information

15 212: Principles of Programming. Some Notes on Induction

15 212: Principles of Programming. Some Notes on Induction 5 22: Principles of Programming Some Notes on Induction Michael Erdmann Spring 20 These notes provide a brief introduction to induction for proving properties of ML programs. We assume that the reader

More information

Datatype declarations

Datatype 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 information

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions PROGRAMMING IN HASKELL CS-205 - Chapter 6 - Recursive Functions 0 Introduction As we have seen, many functions can naturally be defined in terms of other functions. factorial :: Int Int factorial n product

More information

Fall 2018 Lecture N

Fall 2018 Lecture N 15-150 Fall 2018 Lecture N Tuesday, 20 November I m too lazy to figure out the correct number Stephen Brookes midterm2 Mean: 79.5 Std Dev: 18.4 Median: 84 today or, we could procrastinate lazy functional

More information

CS558 Programming Languages

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

More information

CS 188: Artificial Intelligence Fall 2011

CS 188: Artificial Intelligence Fall 2011 CS 188: Artificial Intelligence Fall 2011 Lecture 5: CSPs II 9/8/2011 Dan Klein UC Berkeley Multiple slides over the course adapted from either Stuart Russell or Andrew Moore 1 Today Efficient Solution

More information

Fall 2018 Lecture 1

Fall 2018 Lecture 1 15-150 Fall 2018 Lecture 1 Stephen Brookes 1 Themes functional programming correctness, termination, and performance types, specifications, and proofs evaluation and equivalence referential transparency

More information

CSC236H Lecture 5. October 17, 2018

CSC236H Lecture 5. October 17, 2018 CSC236H Lecture 5 October 17, 2018 Runtime of recursive programs def fact1(n): if n == 1: return 1 else: return n * fact1(n-1) (a) Base case: T (1) = c (constant amount of work) (b) Recursive call: T

More information

MoreIntro_annotated.v. MoreIntro_annotated.v. Printed by Zach Tatlock. Oct 04, 16 21:55 Page 1/10

MoreIntro_annotated.v. MoreIntro_annotated.v. Printed by Zach Tatlock. Oct 04, 16 21:55 Page 1/10 Oct 04, 16 21:55 Page 1/10 * Lecture 02 Infer some type arguments automatically. Set Implicit Arguments. Note that the type constructor for functions (arrow " >") associates to the right: A > B > C = A

More information

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

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

More information

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

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

More information

Con$nuing CPS. COS 326 David Walker Princeton University

Con$nuing CPS. COS 326 David Walker Princeton University Con$nuing CPS COS 326 David Walker Princeton University Last Time We saw that code like this could take up a lot of stack space: let rec sum_to (n:int) : int = if n > 0 then n + sum_to (n-1) else 0 Last

More information

Isabelle s meta-logic. p.1

Isabelle s meta-logic. p.1 Isabelle s meta-logic p.1 Basic constructs Implication = (==>) For separating premises and conclusion of theorems p.2 Basic constructs Implication = (==>) For separating premises and conclusion of theorems

More information

A Functional Space Model. COS 326 David Walker Princeton University

A Functional Space Model. COS 326 David Walker Princeton University A Functional Space Model COS 326 David Walker Princeton University Data type representations: Last Time type tree = Leaf Node of int * tree * tree Leaf: Node(i, left, right): 0 Node 3 left right This Time

More information

4.1 Review - the DPLL procedure

4.1 Review - the DPLL procedure Applied Logic Lecture 4: Efficient SAT solving CS 4860 Spring 2009 Thursday, January 29, 2009 The main purpose of these notes is to help me organize the material that I used to teach today s lecture. They

More information

Week 5 Tutorial Structural Induction

Week 5 Tutorial Structural Induction Department of Computer Science, Australian National University COMP2600 / COMP6260 Formal Methods in Software Engineering Semester 2, 2016 Week 5 Tutorial Structural Induction You should hand in attempts

More information

Lambda Calculus and Type Inference

Lambda Calculus and Type Inference Lambda Calculus and Type Inference Björn Lisper Dept. of Computer Science and Engineering Mälardalen University bjorn.lisper@mdh.se http://www.idt.mdh.se/ blr/ October 13, 2004 Lambda Calculus and Type

More information

Programming Languages

Programming Languages CSE 230: Winter 2008 Principles of Programming Languages Ocaml/HW #3 Q-A Session Push deadline = Mar 10 Session Mon 3pm? Lecture 15: Type Systems Ranjit Jhala UC San Diego Why Typed Languages? Development

More information

CSE 143 Lecture 18. More Recursive Backtracking. slides created by Marty Stepp

CSE 143 Lecture 18. More Recursive Backtracking. slides created by Marty Stepp CSE 143 Lecture 18 More Recursive Backtracking slides created by Marty Stepp http://www.cs.washington.edu/143/ Exercise: Dominoes The game of dominoes is played with small black tiles, each having 2 numbers

More information

Spring 2018 LECTURE 27. Review. Dilsun Kaynar

Spring 2018 LECTURE 27. Review. Dilsun Kaynar 15-150 Spring 2018 LECTURE 27 Review Dilsun Kaynar Advice for the final Review Labs, homeworks, lectures Practice Practice Types, recursion, work and span, induction, equivalence, totality, effects, signatures,

More information

Control in Sequential Languages

Control in Sequential Languages CS 242 2012 Control in Sequential Languages Reading: Chapter 8, Sections 8.1 8.3 (only) Section 7.3 of The Haskell 98 Report, Exception Handling in the I/O Monad, http://www.haskell.org/onlinelibrary/io-13.html

More information

Functional Programming

Functional Programming Functional Programming Function evaluation is the basic concept for a programming paradigm that has been implemented in functional programming languages. The language ML ( Meta Language ) was originally

More information

CSE341 Spring 2016, Midterm Examination April 29, 2016

CSE341 Spring 2016, Midterm Examination April 29, 2016 CSE341 Spring 2016, Midterm Examination April 29, 2016 Please do not turn the page until 10:30. Rules: The exam is closed-book, closed-note, etc. except for one side of one 8.5x11in piece of paper. Please

More information

Higher-Order Functions

Higher-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 information

UCSD CSE 21, Spring 2014 [Section B00] Mathematics for Algorithm and System Analysis

UCSD CSE 21, Spring 2014 [Section B00] Mathematics for Algorithm and System Analysis UCSD CSE 21, Spring 2014 [Section B00] Mathematics for Algorithm and System Analysis Lecture 11 Class URL: http://vlsicad.ucsd.edu/courses/cse21-s14/ Lecture 11 Notes Goals for this week (Tuesday) Linearity

More information

Lecture 2: SML Basics

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

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Winter 2017 Lecture 6a Andrew Tolmach Portland State University 1994-2017 Iteration into Recursion Any iteration can be written as a recursion, e.g. while (c) {e Scala is equivalent

More information

Defining Functions. CSc 372. Comparative Programming Languages. 5 : Haskell Function Definitions. Department of Computer Science University of Arizona

Defining Functions. CSc 372. Comparative Programming Languages. 5 : Haskell Function Definitions. Department of Computer Science University of Arizona Defining Functions CSc 372 Comparative Programming Languages 5 : Haskell Function Definitions Department of Computer Science University of Arizona collberg@gmail.com When programming in a functional language

More information

Logic and Computation Lecture 20 CSU 290 Spring 2009 (Pucella) Thursday, Mar 12, 2009

Logic and Computation Lecture 20 CSU 290 Spring 2009 (Pucella) Thursday, Mar 12, 2009 Logic and Computation Lecture 20 CSU 290 Spring 2009 (Pucella) Thursday, Mar 12, 2009 Note that I change the name of the functions slightly in these notes from what I used in class, to be consistent with

More information

Preliminary Examination I Computer Science 312, Cornell University 6 March 2003

Preliminary Examination I Computer Science 312, Cornell University 6 March 2003 Preliminary Examination I Computer Science 312, Cornell University 6 March 2003 Before starting the exam, write your name on this page and your netid on both this page and the next page. There are 5 problems

More information

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

The design of a programming language for provably correct programs: success and failure The design of a programming language for provably correct programs: success and failure Don Sannella Laboratory for Foundations of Computer Science School of Informatics, University of Edinburgh http://homepages.inf.ed.ac.uk/dts

More information

SEARCHING, SORTING, AND ASYMPTOTIC COMPLEXITY. Lecture 11 CS2110 Spring 2016

SEARCHING, SORTING, AND ASYMPTOTIC COMPLEXITY. Lecture 11 CS2110 Spring 2016 1 SEARCHING, SORTING, AND ASYMPTOTIC COMPLEXITY Lecture 11 CS2110 Spring 2016 Time spent on A2 2 Histogram: [inclusive:exclusive) [0:1): 0 [1:2): 24 ***** [2:3): 84 ***************** [3:4): 123 *************************

More information

Handout 2 August 25, 2008

Handout 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 information

Recursion. What is Recursion? Simple Example. Repeatedly Reduce the Problem Into Smaller Problems to Solve the Big Problem

Recursion. What is Recursion? Simple Example. Repeatedly Reduce the Problem Into Smaller Problems to Solve the Big Problem Recursion Repeatedly Reduce the Problem Into Smaller Problems to Solve the Big Problem What is Recursion? A problem is decomposed into smaller sub-problems, one or more of which are simpler versions of

More information

15 150: Principles of Functional Programming. Exceptions

15 150: Principles of Functional Programming. Exceptions 15 150: Principles of Functional Programming Exceptions Michael Erdmann Spring 2018 1 Topics Exceptions Referential transparency, revisited Examples to be discussed: Dealing with arithmetic errors Making

More information

CMSC 330: Organization of Programming Languages. Formal Semantics of a Prog. Lang. Specifying Syntax, Semantics

CMSC 330: Organization of Programming Languages. Formal Semantics of a Prog. Lang. Specifying Syntax, Semantics Recall Architecture of Compilers, Interpreters CMSC 330: Organization of Programming Languages Source Scanner Parser Static Analyzer Operational Semantics Intermediate Representation Front End Back End

More information

Recursion. Recursion is: Recursion splits a problem:

Recursion. Recursion is: Recursion splits a problem: Recursion Recursion Recursion is: A problem solving approach, that can... Generate simple solutions to... Certain kinds of problems that... Would be difficult to solve in other ways Recursion splits a

More information

CSCI 136 Data Structures & Advanced Programming. Lecture 14 Fall 2018 Instructor: Bills

CSCI 136 Data Structures & Advanced Programming. Lecture 14 Fall 2018 Instructor: Bills CSCI 136 Data Structures & Advanced Programming Lecture 14 Fall 2018 Instructor: Bills Announcements Mid-Term Review Session Monday (10/15), 7:00-8:00 pm in TPL 203 No prepared remarks, so bring questions!

More information

CMPSCI 187: Programming With Data Structures. Lecture #15: Thinking Recursively David Mix Barrington 10 October 2012

CMPSCI 187: Programming With Data Structures. Lecture #15: Thinking Recursively David Mix Barrington 10 October 2012 CMPSCI 187: Programming With Data Structures Lecture #15: Thinking Recursively David Mix Barrington 10 October 2012 Thinking Recursively Recursive Definitions, Algorithms, and Programs Computing Factorials

More information

Currying fun f x y = expression;

Currying fun f x y = expression; Currying ML chooses the most general (least-restrictive) type possible for user-defined functions. Functions are first-class objects, as in Scheme. The function definition fun f x y = expression; defines

More information

CSCI-GA Scripting Languages

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

More information

Mathematics for Computer Scientists 2 (G52MC2)

Mathematics for Computer Scientists 2 (G52MC2) Mathematics for Computer Scientists 2 (G52MC2) L07 : Operations on sets School of Computer Science University of Nottingham October 29, 2009 Enumerations We construct finite sets by enumerating a list

More information

www.thestudycampus.com Recursion Recursion is a process for solving problems by subdividing a larger problem into smaller cases of the problem itself and then solving the smaller, more trivial parts. Recursion

More information

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. 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 information

Lecture Notes on Program Equivalence

Lecture Notes on Program Equivalence Lecture Notes on Program Equivalence 15-312: Foundations of Programming Languages Frank Pfenning Lecture 24 November 30, 2004 When are two programs equal? Without much reflection one might say that two

More information

Standard ML. Data types. ML Datatypes.1

Standard 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 information

Lecture Chapter 6 Recursion as a Problem Solving Technique

Lecture Chapter 6 Recursion as a Problem Solving Technique Lecture Chapter 6 Recursion as a Problem Solving Technique Backtracking 1. Select, i.e., guess, a path of steps that could possibly lead to a solution 2. If the path leads to a dead end then retrace steps

More information

Backtracking. Chapter 5

Backtracking. Chapter 5 1 Backtracking Chapter 5 2 Objectives Describe the backtrack programming technique Determine when the backtracking technique is an appropriate approach to solving a problem Define a state space tree for

More information

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

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

More information

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

More information

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

More information

Solving NP-hard Problems on Special Instances

Solving NP-hard Problems on Special Instances Solving NP-hard Problems on Special Instances Solve it in poly- time I can t You can assume the input is xxxxx No Problem, here is a poly-time algorithm 1 Solving NP-hard Problems on Special Instances

More information

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

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

More information

INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION. Instructors: Crista Lopes Copyright Instructors.

INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION. Instructors: Crista Lopes Copyright Instructors. INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION Instructors: Crista Lopes Copyright Instructors. Topics Recursion Higher-order functions Continuation-Passing Style Monads (take 1) Identity Monad Maybe

More information

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

Problem Set 2 Solutions

Problem Set 2 Solutions CS235 Languages and Automata Handout # 7 Prof. Lyn Turbak October 16, 2007 Wellesley College Problem Set 2 Solutions Problem 6 from PS1 [45 points] You were asked to determine the sizes of various sets

More information

CSE341 Spring 2016, Midterm Examination April 29, 2016

CSE341 Spring 2016, Midterm Examination April 29, 2016 CSE341 Spring 2016, Midterm Examination April 29, 2016 Please do not turn the page until 10:30. Rules: The exam is closed-book, closed-note, etc. except for one side of one 8.5x11in piece of paper. Please

More information

CS 135 Fall 2018 Final Exam Review. CS 135 Fall 2018 Final Exam Review 1

CS 135 Fall 2018 Final Exam Review. CS 135 Fall 2018 Final Exam Review 1 CS 135 Fall 2018 Final Exam Review CS 135 Fall 2018 Final Exam Review 1 Final Exam Information The final exam will be held on Saturday, December 15 th 9:00AM - 11:30AM in the PAC Check your exam seating

More information

Shell CSCE 314 TAMU. Functions continued

Shell CSCE 314 TAMU. Functions continued 1 CSCE 314: Programming Languages Dr. Dylan Shell Functions continued 2 Outline Defining Functions List Comprehensions Recursion 3 A Function without Recursion Many functions can naturally be defined in

More information

CSE505, Fall 2012, Midterm Examination October 30, 2012

CSE505, Fall 2012, Midterm Examination October 30, 2012 CSE505, Fall 2012, Midterm Examination October 30, 2012 Rules: The exam is closed-book, closed-notes, except for one side of one 8.5x11in piece of paper. Please stop promptly at Noon. You can rip apart

More information

SEARCHING, SORTING, AND ASYMPTOTIC COMPLEXITY

SEARCHING, SORTING, AND ASYMPTOTIC COMPLEXITY 1 A3 and Prelim 2 SEARCHING, SORTING, AND ASYMPTOTIC COMPLEXITY Lecture 11 CS2110 Fall 2016 Deadline for A3: tonight. Only two late days allowed (Wed-Thur) Prelim: Thursday evening. 74 conflicts! If you

More information

Chapter 3 Programming with Recursion

Chapter 3 Programming with Recursion Plan Chapter 3 Programming with Recursion 1. Examples... 3.2 2. Correctness... 3.5 3. Construction methodology... 3.13 4. Forms of recursion... 3.16 Sven-Olof Nyström/IT Dept/Uppsala University FP 3.1

More information

SOFTWARE VERIFICATION AND COMPUTER PROOF (lesson 1) Enrico Tassi Inria Sophia-Antipolis

SOFTWARE VERIFICATION AND COMPUTER PROOF (lesson 1) Enrico Tassi Inria Sophia-Antipolis SOFTWARE VERIFICATION AND COMPUTER PROOF (lesson 1) Enrico Tassi Inria Sophia-Antipolis Who am I? 1. I'm a researcher at Inria 2. I work on proof assistants, the kind of tools that we will be using for

More information