Comp 311 Functional Programming. Eric Allen, Two Sigma Investments Robert Corky Cartwright, Rice University Sagnak Tasirlar, Two Sigma Investments

Similar documents
Sorting: Given a list A with n elements possessing a total order, return a list with the same elements in non-decreasing order.

Comp 311 Functional Programming. Eric Allen, Two Sigma Investments Robert Corky Cartwright, Rice University Sağnak Taşırlar, Two Sigma Investments

Exercise 1: Graph coloring (10 points)

Functional Programming

CompSci 220. Programming Methodology 12: Functional Data Structures

CSE 130, Fall 2006: Final Examination

MORE SCHEME. 1 What Would Scheme Print? COMPUTER SCIENCE MENTORS 61A. October 30 to November 3, Solution: Solutions begin on the following page.

List are immutable Lists have recursive structure Lists are homogeneous

Scala Style Guide Spring 2018

Algorithm classification

Topic 5: Examples and higher-order functions

Programming Principles

Programming Principles

Advanced Type System Features Tom Schrijvers. Leuven Haskell User Group

Computer Science 1001.py. Lecture 11: Recursion and Recursive Functions

CS558 Programming Languages

Linked lists and the List class

BM267 - Introduction to Data Structures

Strings are not collections, but they behave like them in almost every way. For example,

Instructors: Amir Rubinstein, Daniel Deutch Teaching Assistants: Amir Gilad, Michal Kleinbort. Founding instructor: Benny Chor

Sorting and Searching

Generative and accumulative recursion. What is generative recursion? Example revisited: GCD. Readings: Sections 25, 26, 27, 30, 31

Lecture 11: Recursion (2) - Binary search, Quicksort, Mergesort

Lecture 19 Sorting Goodrich, Tamassia

QuickSort

ITEC2620 Introduction to Data Structures

Algorithms Interview Questions

More Functions on Lists

CompSci 220. Programming Methodology 16: Understanding FP Error Handling Part 2

Trees. Eric McCreath

17/05/2018. Outline. Outline. Divide and Conquer. Control Abstraction for Divide &Conquer. Outline. Module 2: Divide and Conquer

Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7

UNIT 5C Merge Sort Principles of Computing, Carnegie Mellon University

Collections and Combinatorial Search

UNIT 5C Merge Sort. Course Announcements

If we have a call. Now consider fastmap, a version of map that uses futures: Now look at the call. That is, instead of

April 2 to April 4, 2018

CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1

Sorting is a problem for which we can prove a non-trivial lower bound.

Sorting Goodrich, Tamassia Sorting 1

Merge Sort Goodrich, Tamassia Merge Sort 1

About this exam review

DATA STRUCTURES AND ALGORITHMS

Copyright 2012 by Pearson Education, Inc. All Rights Reserved.

Unit-2 Divide and conquer 2016

Computer Science 1001.py. Lecture 10B : Recursion and Recursive Functions

From Templates to Folds

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

Sorting. Sorting in Arrays. SelectionSort. SelectionSort. Binary search works great, but how do we create a sorted array in the first place?

Unit 6 Chapter 15 EXAMPLES OF COMPLEXITY CALCULATION

Prolog. GNU Prolog ( SWI-Prolog (

Sorting L7.2 Recall linear search for an element in an array, which is O(n). The divide-and-conquer technique of binary search divides the array in ha

// Body of shortestlists starts here y flatmap { case Nil => Nil case x :: xs => findshortest(list(x), xs)

Searching and Sorting

ITEC2620 Introduction to Data Structures

Overview. Elements of Programming Languages. Advanced constructs. Motivating inner class example

Sorting. Task Description. Selection Sort. Should we worry about speed?

8. Write an example for expression tree. [A/M 10] (A+B)*((C-D)/(E^F))

Quick-Sort. Quick-Sort 1

ECE 242 Data Structures and Algorithms. Advanced Sorting II. Lecture 17. Prof.

ECE 242 Data Structures and Algorithms. Advanced Sorting I. Lecture 16. Prof.

Reading for this lecture (Goodrich and Tamassia):

Quicksort. Repeat the process recursively for the left- and rightsub-blocks.

Lecture 21: Functional Programming in Python. List Comprehensions

12/30/2013 S. NALINI,AP/CSE

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

CS102 Sorting - Part 2

Control Structures. Christopher Simpkins CS 3693, Fall Chris Simpkins (Georgia Tech) CS 3693 Scala / 1

Data Structures, Algorithms & Data Science Platforms

CS205: Scalable Software Systems

Assignment 2. CS 234 Fall 2018 Sandy Graham. Create()

Practically Functional. Daniel Spiewak

Advanced Sorting. Merge Sort Quick Sort Radix Sort

Lecture 14: General Problem-Solving Methods

Declarative concurrency. March 3, 2014

DO NOT. UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N.

Scala : an LLVM-targeted Scala compiler

Outline. Collections Arrays vs. Lists Functions using Arrays/Lists Higher order functions using Arrays/Lists

G Programming Languages - Fall 2012

Algorithms and Data Structures (INF1) Lecture 7/15 Hua Lu

DM536 Introduction to Programming. Peter Schneider-Kamp.

Notes from a Short Introductory Lecture on Scala (Based on Programming in Scala, 2nd Ed.)

Module 08: Searching and Sorting Algorithms

Presentation for use with the textbook, Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015

Presentation for use with the textbook, Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, Merge Sort & Quick Sort

CSE 373 Final Exam 3/14/06 Sample Solution

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Quick-Sort fi fi fi 7 9. Quick-Sort Goodrich, Tamassia

Programming II (CS300)

Lab 6 Sorting. Sup Biotech 3 Python. Pierre Parutto

Graphs & Digraphs Tuesday, November 06, 2007

CSI33 Data Structures

CS205: Scalable Software Systems

CS 2340 Objects and Design - Scala

Sorting and Selection

CS301 - Data Structures Glossary By

DIVIDE AND CONQUER ALGORITHMS ANALYSIS WITH RECURRENCE EQUATIONS


CSC148-Section:L0301

Computation Abstraction Going beyond programming language glue, or what we've missed from FP for so long in mainstream

Transcription:

Comp 311 Functional Programming Eric Allen, Two Sigma Investments Robert Corky Cartwright, Rice University Sagnak Tasirlar, Two Sigma Investments

How to Decide Between Structural and Generative Recursion Structural recursion is typically: Easier to design Easier to understand Generative recursion can be faster (sometimes!)

How to Decide Between Structural and Generative Recursion As a general guideline: Start with structural recursion If it turns out to be too slow: Explore generatively recursive approaches

Strategies for Generative Recursion

Binary Search The strategy of searching over a sequence by breaking in half and searching over just one of them Our search for blue-eyed ancestors falls into this category We could also use binary search for root finding Newton s Method could be viewed as an optimization on binary search for root finding

Divide and Conquer The strategy of breaking a problem into smaller sub-problems of the same type Quicksort falls into this category

Quicksort def quicksort(xs: List[Int]): List[Int] = { xs match { case Nil => Nil case x :: xs => { val (smaller, larger) = separate(xs, x) quicksort(smaller) ++ List(x) ++ quicksort(larger)

Quicksort def quicksort(xs: List[Int]): List[Int] = { xs match { case Nil => Nil case x :: xs => { val (smaller, larger) = separate(xs, x) quicksort(smaller) ++ List(x) ++ quicksort(larger) Trivially solvable

Quicksort def quicksort(xs: List[Int]): List[Int] = { xs match { case Nil => Nil case x :: xs => { val (smaller, larger) = separate(xs, x) quicksort(smaller) ++ List(x) ++ quicksort(larger) Sub-problems

Quicksort def quicksort(xs: List[Int]): List[Int] = { xs match { case Nil => Nil case x :: xs => { val (smaller, larger) = separate(xs, x) quicksort(smaller) ++ List(x) ++ quicksort(larger) Combination

Separate def separate(xs: List[Int], x: Int): (List[Int], List[Int]) = { xs match { case Nil => (Nil, Nil) case y :: ys => { val (smaller, larger) = separate(ys, x) if (y < x) (y :: smaller, larger) else (smaller, y :: larger)

Description and Termination Argument /** * Recurs on two sublists of the given list: * All elements smaller than a given pivot * All elements at least as large as the pivot * Appends the recursive solutions. * Because each sublist is strictly smaller * (the pivot was extracted from the list), * we eventually recur on an empty list. */ def quicksort(xs: List[Int]): List[Int] = {

Backtracking Algorithms

Graph Algorithms Many problems can be expressed as traversals or computations over graphs Travel planning Circuit design Social networks etc.

Graph Algorithms We consider the problem of finding a path from one vertex to another in a graph

Data Analysis and Design We model graphs as Maps of Strings to Lists of Strings case class Graph(elements: (String, List[String])*) extends Function1[String, List[String]] { val _elements = Map(elements:_*) def apply(s: String) = _elements(s)

Data Analysis and Design We model graphs as Maps of Strings to Lists of Strings val samplegraph = new Graph ("A" -> List("E", "B"), "B" -> List("A"), "C" -> List("D"), "D" -> List(), "E" -> List("C", "F"), "F" -> List("A", "G"), "G" -> List())

What is a Trivially Solvable Problem? If the start and end vertices are identical

How Do We Generate Sub- Problems? Find nodes connected to start and recur

How Do We Relate the Solutions? We need only find one solution; no need to combine multiple solutions

Contract Attempt 1 /** * Create a path from start to finish in G */ def findroute(start: String, end: String, graph: Graph): List[String] But what if there is no path?

Options Often the result of a computation is that no satisfactory value could be found Lookup in a table with a key that does not exist Attempting to find a path that does not exist

Scala Options abstract class Option[+A] { object None extends Option[Nothing] { class Some[+A](val contained: A) extends Option[A] {

Options Are Monads! abstract class Option[+A] { def flatmap[b](f: (A) Option[B]): Option[B] def map[b](f: (A) B): Option[B] def withfilter(p: (A) Boolean): FilterMonadic[A, collection.iterable[a]]

Contract Attempt 2 /** * Create a path from start to finish in G, if * it exists. */ def findroute(start: String, end: String, graph: Graph): Option[List[String]]

Reduce to Backtracking Cases def findroute(start: String, end: String, graph: Graph): Option[List[String]] = { if (start == end) Some(List(end)) else for (route <- routefromorigins(graph(start), end, graph)) yield start :: route

Recursive Sub-Problems def routefromorigins(origins: List[String], destination: String, graph: Graph): Option[List[String]] = { origins match { case Nil => None case origin :: origins => { findroute(origin, destination, graph) match { case None => routefromorigins(origins, destination,graph) case Some(route) => Some(route)

Termination routefromorigins is structurally recursive: It terminates provided that findroute terminates But findroute terminates only if there are no cycles in the graph it traverses