Shell CSCE 314 TAMU. Functions continued

Similar documents
PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions

Shell CSCE 314 TAMU. Higher Order Functions

Shell CSCE 314 TAMU. Haskell Functions

PROGRAMMING IN HASKELL. Chapter 5 - List Comprehensions

CSCE 314 Programming Languages

Programming Languages 3. Definition and Proof by Induction

Introduction to Programming: Lecture 6

The List Datatype. CSc 372. Comparative Programming Languages. 6 : Haskell Lists. Department of Computer Science University of Arizona

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

A general introduction to Functional Programming using Haskell

An introduction introduction to functional functional programming programming using usin Haskell

Informatics 1 Functional Programming Lecture 11. Data Representation. Don Sannella University of Edinburgh

Lecture 2: List algorithms using recursion and list comprehensions

Week 5 Tutorial Structural Induction

Standard prelude. Appendix A. A.1 Classes

CSCE 314 Programming Languages Functors, Applicatives, and Monads

More fun with recursion

Programming in Haskell Aug-Nov 2015

Haskell Types, Classes, and Functions, Currying, and Polymorphism

Informatics 1 Functional Programming Lecture 12. Data Abstraction. Don Sannella University of Edinburgh

INTRODUCTION TO FUNCTIONAL PROGRAMMING

INTRODUCTION TO HASKELL

Topic 5: Examples and higher-order functions

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

Functional Programming TDA 452, DIT 142

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

Functional Programming in Haskell Part I : Basics

The University of Nottingham

1 The smallest free number

Haskell through HUGS THE BASICS

Part 20. Sorting and Selection

Programming Language Concepts: Lecture 14

Practical Haskell. An introduction to functional programming. July 21, Practical Haskell. Juan Pedro Villa-Isaza. Introduction.

A Second Look At ML. Chapter Seven Modern Programming Languages, 2nd ed. 1

Haskell 101. (Version 1 (July 18, 2012)) Juan Pedro Villa Isaza

CSCE 314 Programming Languages

Watch out for the arrows. Recollecting Haskell, Part V. A start on higher types: Mapping, 1. A start on higher types: Mapping, 2.

EDAF40. 2nd June :00-19:00. WRITE ONLY ON ONE SIDE OF THE PAPER - the exams will be scanned in and only the front/ odd pages will be read.

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

QuickCheck, SmallCheck & Reach: Automated Testing in Haskell. Tom Shackell

CS 457/557: Functional Languages

Then you were asked to paint another fence that is 2m high and 400m long for the price of $80. Should you accept it?

CSc 520 Principles of Programming Languages. Currying Revisited... Currying Revisited. 16: Haskell Higher-Order Functions

CSc 372. Comparative Programming Languages. 11 : Haskell Higher-Order Functions. Department of Computer Science University of Arizona

Foundations of Computation

Functional Programming. Overview. Topics. Definition n-th Fibonacci Number. Graph

CS 320: Concepts of Programming Languages

Functional Programming TDA 452, DIT 142

Programming Languages Fall 2013

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Basics

CS 340 Spring 2019 Midterm Exam

CSCE 314 Programming Languages

CSc 372 Comparative Programming Languages

CSc 372. Comparative Programming Languages. 8 : Haskell Function Examples. Department of Computer Science University of Arizona

FUNCTIONAL PEARLS The countdown problem

Introduction to Programming, Aug-Dec 2006

Haskell: From Basic to Advanced. Part 3 A Deeper Look into Laziness

Efficient Mergesort. Christian Sternagel. August 28, 2014

Lecture 19: Functions, Types and Data Structures in Haskell

Patterns The Essence of Functional Programming

Informatics 1 Functional Programming Lecture 7. Map, filter, fold. Don Sannella University of Edinburgh

Haskell Introduction Lists Other Structures Data Structures. Haskell Introduction. Mark Snyder

A tour of the Haskell Prelude

School of Computer Science

Haskell: From Basic to Advanced. Part 2 Type Classes, Laziness, IO, Modules

Informatics 1 Functional Programming Lecture 4. Lists and Recursion. Don Sannella University of Edinburgh

A Sudoku Solver (1A) Richard Bird Implementation. Young Won Lim 11/15/16

CS 320: Concepts of Programming Languages

An Introduction to Programming in Haskell. Gabriel J. Ferrer Hendrix College

General Computer Science (CH ) Fall 2016 SML Tutorial: Practice Problems

Functional Programming and Haskell

Programming Paradigms Written Exam (6 CPs)

Set Haskell Exercises

Advanced Type System Features Tom Schrijvers. Leuven Haskell User Group

CSE 130: Programming Languages. Polymorphism. Ranjit Jhala UC San Diego

Haskell Overview II (2A) Young Won Lim 8/23/16

Let s Talk About Logic

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

List Processing in Ocaml

! " Haskell Expressions are treated as: !" Thunks. !" Closures. !" Delayed Computations. !" Suspensions. ! " Expressions are evaluated: !

Solution sheet 1. Introduction. Exercise 1 - Types of values. Exercise 2 - Constructors

CSCE 314 Programming Languages

Functional Programming in Haskell for A level teachers

Reasoning about programs. Chapter 9 of Thompson

301AA - Advanced Programming

List Functions, and Higher-Order Functions

Logic - CM0845 Introduction to Haskell

Haskell Overview II (2A) Young Won Lim 8/9/16

Extended Static Checking for Haskell (ESC/Haskell)

Searching in General

Testing. Wouter Swierstra and Alejandro Serrano. Advanced functional programming - Lecture 2. [Faculty of Science Information and Computing Sciences]

A Sudoku Solver Pruning (3A)

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

Mathematical Induction

Fall 2018 Lecture N

CSCE 314 Programming Languages. Interactive Programming: I/O

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))

CS 209 Functional Programming

Lecture 1 Functional Programming

Transcription:

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 terms of other functions. factorial :: Int Int factorial n product [1..n] factorial maps any integer n to the product of the integers between 1 and n Expressions are evaluated by a stepwise process of applying functions to their arguments. For example: factorial 4 product [1..4] product [1,2,3,4] 1*2*3*4 24

Recursive Functions Functions can also be defined in terms of themselves. Such functions are called recursive. factorial 0 1 factorial n n * factorial (n-1) factorial 3 3 * factorial 2 3 * (2 * factorial 1) 6 3 * (2 * (1 * factorial 0)) 3 * (2 * (1 * 1)) 3 * (2 * 1) 3 * 2 factorial maps 0 to 1, and any other positive integer to the product of itself and the factorial of its predecessor. 4

5 Note: The base case factorial 0 1 is appropriate because 1 is the identity for multiplication: 1*x x x*1. Shell CSCE 314 TAMU The recursive definition diverges on integers < 0 because the base case is never reached: > factorial (-1) Error: Control stack overflow

6 Why is Recursion Useful? Some functions, such as factorial, are simpler to define in terms of other functions. As we shall see, however, many functions can naturally be defined in terms of themselves. Properties of functions defined using recursion can be proved using the simple but powerful mathematical technique of induction.

7 Recursion on Lists Lists have naturally a recursive structure. Consequently, recursion is used to define functions on lists. product :: [Int] Int product [] 1 product (n:ns) n * product ns product [2,3,4] 2 * product [3,4] 2 * (3 * product [4]) 2 * (3 * (4 * product [])) 2 * (3 * (4 * 1)) 24 product maps the empty list to 1, and any non-empty list to its head multiplied by the product of its tail.

8 Using the same pattern of recursion as in product we can define the length function on lists. length :: [a] Int length [] 0 length (_:xs) 1 + length xs length maps the empty list to 0, and any non-empty list to the successor of the length of its tail. length [1,2,3] 1 + length [2,3] 1 + (1 + length [3]) 1 + (1 + (1 + length [])) 1 + (1 + (1 + 0)) 3

9 Using a similar pattern of recursion we can define the reverse function on lists. reverse reverse [] [] :: [a] [a] reverse (x:xs) reverse xs ++ [x] reverse [1,2,3] reverse [2,3] ++ [1] (reverse [3] ++ [2]) ++ [1] ((reverse [] ++ [3]) ++ [2]) ++ [1] (([] ++ [3]) ++ [2]) ++ [1] [3,2,1] reverse maps the empty list to the empty list, and any non-empty list to the reverse of its tail appended to its head. Shell CSCE 314 TAMU

Multiple Arguments Functions with more than one argument can also be defined using recursion. For example: Zipping the elements of two lists: zip :: [a] [b] [(a,b)] zip [] _ [] zip _ [] [] zip (x:xs) (y:ys) (x,y) : zip xs ys Remove the first n elements from a list: Appending two lists: drop :: Int [a] [a] drop n xs n < 0 xs drop _ [] [] drop n (_:xs) drop (n-1) xs (++) :: [a] [a] [a] [] ++ ys ys (x:xs) ++ ys x : (xs ++ ys) 10

11 Laziness Revisited Laziness interacts with recursion in interesting ways. For example, what does the following function do? numberlist xs zip [0..] xs > numberlist abcd [(0, a ),(1, b ),(2, c ),(3, d )]

Laziness with Recursion Recursion combined with lazy evaluation can be tricky; stack overflows may result in the following example: expensivelen [] 0 expensivelen (_:xs) 1 + expensivelen xs stillexpensivelen ls len 0 ls where len z [] z cheaplen ls len 0 ls len z (_:xs) len (z+1) xs where len z [] z len z (_:xs) let z z+1 in z `seq` len z xs > expensivelen [1..10000000] -- takes quite a while > stillexpensivelen [1..10000000] -- also takes a long time > cheaplen [1..10000000] -- less memory and time Shell CSCE 314 TAMU 12

13 Quicksort The quicksort algorithm for sorting a list of integers can be specified by the following two rules: The empty list is already sorted; Non-empty lists can be sorted by sorting the tail values the head, sorting the tail values > the head, and then appending the resulting lists on either side of the head value.

14 Using recursion, this specification can be translated directly into an implementation: qsort :: [Int] -> [Int] qsort [] [] qsort (x:xs) qsort smaller ++ [x] ++ qsort larger where smaller [a a <- xs, a < x] larger [b b <- xs, b > x] Note: This is probably the simplest implementation of quicksort in any programming language!

15 For example (abbreviating qsort as q): q [3,2,4,1,5]

16 Exercises (1) Without looking at the standard prelude, define the following library functions using recursion: Decide if all logical values in a list are true: and :: [Bool] Bool and [] True and (b:bs) b && and bs Concatenate a list of lists: concat :: [[a]] [a] concat [] [] concat (xs:xss) xs ++ concat xss

Produce a list with n identical elements: replicate :: Int a [a] replicate 0 _ [] replicate n x x : replicate (n-1) x Select the nth element of a list: (!!) :: [a] Int a (!!) (x:_) 0 x (!!) (_:xs) n (!!) xs (n-1) Decide if a value is an element of a list: elem :: Eq a a [a] Bool elem x [] False elem x (y:ys) xy True otherwise elem x ys 17

18 (2) Define a recursive function merge :: [Int] [Int] [Int] merge [] ys ys merge xs [] xs merge (x:xs) (y:ys) if x < y then x: merge xs (y:ys) else y: merge (x:xs) ys that merges two sorted lists of integers to give a single sorted list. For example: > merge [2,5,6] [1,3,4] [1,2,3,4,5,6]

19 (3) Define a recursive function msort :: [Int] [Int] that implements merge sort, which can be specified by the following two rules: 1. Lists of length 1 are already sorted; 2. Other lists can be sorted by sorting the two halves and merging the resulting lists. halves xs splitat (length xs `div` 2) xs msort [] [] msort [x] [x] msort xs merge (msort ys) (msort zs) where (ys,zs) halves xs

20 Exercises + Some answers (1) Without looking at the standard prelude, define the following library functions using recursion: Decide if all logical values in a list are true: and :: [Bool] Bool and [] True and (b:bs) b && and bs Concatenate a list of lists: concat :: [[a]] [a] concat [] [] concat (xs:xss) xs ++ concat xss

Produce a list with n identical elements: replicate :: Int a [a] replicate 0 _ [] replicate n x x : replicate (n-1) x Select the nth element of a list: (!!) :: [a] Int a (!!) (x:_) 0 x (!!) (_:xs) n (!!) xs (n-1) Decide if a value is an element of a list: elem :: Eq a a [a] Bool elem x [] False elem x (y:ys) xy True otherwise elem x ys 21

22 (2) Define a recursive function merge :: [Int] [Int] [Int] merge [] ys ys merge xs [] xs merge (x:xs) (y:ys) if x < y then x: merge xs (y:ys) else y: merge (x:xs) ys that merges two sorted lists of integers to give a single sorted list. For example: > merge [2,5,6] [1,3,4] [1,2,3,4,5,6]

23 (3) Define a recursive function msort :: [Int] [Int] that implements merge sort, which can be specified by the following two rules: 1. Lists of length 1 are already sorted; 2. Other lists can be sorted by sorting the two halves and merging the resulting lists. halves xs splitat (length xs `div` 2) xs msort [] [] msort [x] [x] msort xs merge (msort ys) (msort zs) where (ys,zs) halves xs