Cs536 Functional Programming 16/13/2015 Lecture #2.5 Today’s Topics A Few Less Trivial Examples – Numerical Functions »Differentiation and square root.

Slides:



Advertisements
Similar presentations
CS 410 Applied Algorithms Applied Algorithms Lecture #7 Counting.
Advertisements

Haskell Chapter 5, Part I. Topics  Higher Order Functions  map, filter  Infinite lists Get out a piece of paper… we’ll be doing lots of tracing.
Chapter 6 Problem Solving and Algorithm Design. 2 Phase Interactions.
Section 4.1: Primes, Factorization, and the Euclidean Algorithm Practice HW (not to hand in) From Barr Text p. 160 # 6, 7, 8, 11, 12, 13.
© M. Winter COSC 4P41 – Functional Programming Patterns of computation over lists Applying to all – mapping map :: (a -> b) -> [a] -> [b] map f.
Pearls of Functional Algorithm Design Chapter 2 1 Roger L. Costello July 2011.
Searching Kruse and Ryba Ch and 9.6. Problem: Search We are given a list of records. Each record has an associated key. Give efficient algorithm.
Sorting Algorithms. Motivation Example: Phone Book Searching Example: Phone Book Searching If the phone book was in random order, we would probably never.
CMPS1371 Introduction to Computing for Engineers SORTING.
Sorting Chapter Sorting Consider list x 1, x 2, x 3, … x n We seek to arrange the elements of the list in order –Ascending or descending Some O(n.
CPSC 171 Introduction to Computer Science More Efficiency of Algorithms.
Fall 2008Programming Development Techniques 1 Topic 3 Linear Recursion and Iteration September 2008.
Higher-Order Functions Koen Lindström Claessen. What is a “Higher Order” Function? A function which takes another function as a parameter. Examples map.
CSE115/ENGR160 Discrete Mathematics 03/03/11 Ming-Hsuan Yang UC Merced 1.
CS 206 Introduction to Computer Science II 10 / 14 / 2009 Instructor: Michael Eckmann.
Chapter 19 Recursion.
Algorithm Efficiency and Sorting
Cse536 Functional Programming 1 6/28/2015 Lecture #3, Oct 4, 2004 Reading Assignments –Finish chapter 2 and begin Reading chapter 3 of the Text Today’s.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 14 Recursion.
CS 206 Introduction to Computer Science II 10 / 08 / 2008 Instructor: Michael Eckmann.
Cse536 Functional Programming 1 7/14/2015 Lecture #2, Sept 29, 2004 Reading Assignments –Begin Chapter 2 of the Text Home work #1 can be found on the webpage,
1 Lab 2 CSIT-120 Fall 2000 Session II-A (September 14th) Operations on Data Lab Exercise 2-A Data Types Variables Lab Exercise 2-B Session II-B (September.
MONEY By: Jerrica Graves COINS A penny is copper and worth $0.01 one cent to the dollar. A nickel is silver and worth$0.05 five cents to the dollar.
Functional Programming Lecture 4 - More Lists Muffy Calder.
Ones group Thousands group Millions group Billions group Trillions group Three- Digit Groups (separated by commas) CHAPTER.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Computing with Numbers CSC 161: The Art of Programming Prof. Henry Kautz 9/14/2009.
Tuples and Lists Lecture 3, Programmeringsteknik del A.
Computer Science 111 Fundamentals of Programming I Number Systems.
Math Review Show each amount using the fewest number of coins. 98¢ pennies nickels dimes quarters 1.
Recursion l Powerful Tool l Useful in simplifying a problem (hides details of a problem) l The ability of a function to call itself l A recursive call.
Computer Science 101 Fast Searching and Sorting. Improving Efficiency We got a better best case by tweaking the selection sort and the bubble sort We.
Counting Coins. The Basics Quarter 25 cents Dime 10 cents.
The Fundamentals: Algorithms, the Integers & Matrices.
CS 206 Introduction to Computer Science II 02 / 23 / 2009 Instructor: Michael Eckmann.
Let’s Learn About Money!
CS 361 – Chapters 8-9 Sorting algorithms –Selection, insertion, bubble, “swap” –Merge, quick, stooge –Counting, bucket, radix How to select the n-th largest/smallest.
Chapter Algorithms 3.2 The Growth of Functions 3.3 Complexity of Algorithms 3.4 The Integers and Division 3.5 Primes and Greatest Common Divisors.
Name the United States Coins Count the Pennies 10 ¢
MATH AND MONEY.
Computer Science 101 Fast Algorithms. What Is Really Fast? n O(log 2 n) O(n) O(n 2 )O(2 n )
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
Recursion on Lists Lecture 5, Programmeringsteknik del A.
Data Structures & Algorithms CHAPTER 1 Introduction Ms. Manal Al-Asmari.
Sorting. Sorting Sorting is important! Things that would be much more difficult without sorting: –finding a telephone number –looking up a word in the.
Counting Quarters, Dimes, Nickels, and Pennies Click here to begin Click here to begin.
9.1 Primes and Related Congruence Equations 23 Sep 2013.
Solution of Mid. Term 2009 Consider the following C++ declarations and assignments. int i, j, k ; float x, y ; char c ; bool test ; i = 35 ; j= 5 ; k =
Recursion Higher Order Functions CSCE 314 Spring 2016.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Copyright © 2014 Curt Hill Algorithms From the Mathematical Perspective.
Haskell Chapter 5, Part II. Topics  Review/More Higher Order Functions  Lambda functions  Folds.
List Operations CSCE 314 Spring CSCE 314 – Programming Studio Tuple and List Patterns Pattern matching with wildcards for tuples fst (a, _) = a.
Haskell. GHC and HUGS Haskell 98 is the current version of Haskell GHC (Glasgow Haskell Compiler, version 7.4.1) is the version of Haskell I am using.
0 PROGRAMMING IN HASKELL Typeclasses and higher order functions Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and.
Recursion Powerful Tool
Searching and Sorting Searching algorithms with simple arrays
GC211Data Structure Lecture2 Sara Alhajjam.
COMP 53 – Week Seven Big O Sorting.
Begin at 5. Count by 5s to 100. Begin at 30. Count by 10s to 150.
Divide and Conquer divide and conquer algorithms typically recursively divide a problem into several smaller sub-problems until the sub-problems are.
Fundamentals of Programming I Number Systems
“Human Sorting” It’s a “Problem Solving” game:
Name the United States Coins
Discrete Mathematics CMP-101 Lecture 12 Sorting, Bubble Sort, Insertion Sort, Greedy Algorithms Abdul Hameed
Algorithm Efficiency and Sorting
Quadratic Equations & Square Roots
Chapter 15 Roots and Radicals.
“Human Sorting” It’s a “Problem Solving” game:
Presentation transcript:

Cs536 Functional Programming 16/13/2015 Lecture #2.5 Today’s Topics A Few Less Trivial Examples – Numerical Functions »Differentiation and square root. pp Fokker Notes –Primes. pp 29 Fokker Notes – Display Tool. pp 105 Reade Book –Numbers in Long Hand –Sorting. pp Reade Book –Making Change. Bird & Wadler Reading Assignment Begin reading chapter 2 in “The Haskell School of Expression”

Cs536 Functional Programming 26/13/2015 Numerical Functions Differentiating a function diff :: (Float -> Float) -> (Float -> Float) diff f = f' where f' x = (f (x+h) - f x)/ h h = For Small enough h, good approximation of slope of f h x f f x f(x+h) f x - f(x+h)

Cs536 Functional Programming 36/13/2015 Square Root Again! Repetition on functions until :: (a -> Bool) -> (a -> a) -> a -> a ? until (>10) (+1) 1 11 ? until (< 0.001) (/2.0) Next approximation (again) next n a = (a + (n/a) )/ 2.0 “Almost Equal” infix 5 ~= a ~= b = abs(a-b)<h && abs(b-a)<h where h = Square Root sqrRoot n = until goodenough (next n) 1.0 where goodenough p = p*p ~= n

Cs536 Functional Programming 46/13/2015 Lists of Prime Numbers Does one number evenly divide another? divisible :: Int -> Int -> Bool divisible t n = t `rem` n == 0 denominators :: Int -> [Int] denominators x = filter (divisible x) [1..x] ? denominators 235 [1, 5, 47, 235] A Prime has only two denominators prime :: Int -> Bool prime x = denominators x == [1,x] ? prime 12 False ? prime 37 True

Cs536 Functional Programming 56/13/2015 Primes (cont.) To get a list of primes then generate and prune. primes :: Int -> [ Int ] primes x = filter prime [1..x] ? primes 30 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] What efficiency concerns does this algorithm have?

Cs536 Functional Programming 66/13/2015 A List Display Tool How do we print? [1,2,3,4] pl :: Text a => [a] -> [Char] pl [] = "" pl (x:xs) = (show x) ++ "," ++ (pl xs) ? pl [1,2] 1,2, How do we get rid of the annoying last "," pl :: Text a => [a] -> [Char] pl [] = "" pl [x] = (show x) pl (x:xs) = (show x) ++ "," ++ (pl xs) ? pl [1,2,3] 1,2,3

Cs536 Functional Programming 76/13/2015 List Display Tool (cont.) What about the “[“ and “]” pl :: Text a => [a] -> [Char] pl l = "[" ++ (p l) ++ "]" where p [] = "" p [x] = (show x) p (x:xs) = (show x) ++ "," ++ (p xs) ? pl [1,2,3,4] [1,2,3,4] ? pl [True, not True] [True,False]

Cs536 Functional Programming 86/13/2015 Generalize let “[“ and “]” be parameters pl :: Text a => [Char] -> [Char] -> [Char] -> [a] -> [Char] pl front back sep l = front ++ (p l) ++ back where p [] = "" p [x] = (show x) p (x:xs) = (show x) ++ sep ++ (p xs) ? pl "{" "}" " " [1,2,3] {1 2 3} ? pl "(" ")" "," [1,2,3] (1,2,3)

Cs536 Functional Programming 96/13/2015 Writing out numbers in long hand 342 -> three hundred forty-two Solve for two digit numbers first units = ["one","two","three","four","five", "six","seven","eight", "nine"] teens = ["ten","eleven","twelve","thirteen","fourteen", "fifteen","sixteen", "seventeen","eighteen", "nineteen"] tens = ["twenty","thirty","forty","fifty", "sixty","seventy","eighty","ninety"] Split into tens and ones digits2 n = (n `div` 10, n `mod` 10); ? digits 76 (7,6) ? digits2 345 (34,5)

Cs536 Functional Programming 106/13/2015 Two Digits Solution (cont.) Split into tens and ones then combine in correct way. First a helper function nth (l,n) = l !! n ? nth([1,2,3,4], 2) 3 Now combine {- Good only for two digit numbers -} combine2 (0,0) = "" combine2 (0,u) = nth(units,u-1) combine2 (1,u) = nth(teens,u) combine2 (t,0) = nth(tens,t-2) combine2 (t,u) = (nth(tens,t-2)) ++ "-" ++ (nth(units,u-1)) convert2 = combine2. digits2 ? convert2 34 thirty-four

Cs536 Functional Programming 116/13/2015 Three Digit Solution Split into hundreds and tens digits3 n = (n `div` 100,n `mod` 100) Then Combine combine3 (0,t) = convert2(t) combine3 (h,0) = (nth(units,h-1)) ++ " hundred" combine3 (h,t) = (nth(units,h-1)) ++ " hundred and " ++ (convert2 t) convert3 = combine3. digits3 ? convert3 345 three hundred and forty-five What about thousands ?

Cs536 Functional Programming 126/13/2015 Sorting Insertion Sort –Assume list is already sorted insert item [] = [item] insert item (a:x) = if item < a then item : a : x else a : (insert item x) ? insert 5 [1,3,6,8] [1,3,5,6,8] Now insert each element sort [] = [] sort (x:xs) = insert x (sort xs)

Cs536 Functional Programming 136/13/2015 Does this pattern look familiar? sort [] = [] sort (x:xs) = insert x (sort xs) foldr op e [] = e foldr op e (x:xs) = op x (foldr op e xs) sort = foldr insert []

Cs536 Functional Programming 146/13/2015 Sorting (cont) Here is a definition of quiksort: First a helper function non :: (a -> Bool) -> a -> Bool non f x = not (f x) Divide into two sublists and conquer quiksort :: Ord a => [a] -> [a] quiksort [] = [] quiksort (x:xs) = (quiksort (filter (<=x) xs)) ++ (x : (quiksort (filter (non (<=x)) xs))) ? quiksort [4,8,2,6,1,9] [1, 2, 4, 6, 8, 9]

Cs536 Functional Programming 156/13/2015 Better Quiksort Can we take the two lists computed by two calls to filter and write a function which computes them both in one pass? split :: Ord a => a -> [a] -> ([a],[a]) split pivot [] = ([],[]) split pivot (x:xs) = let (sm,bg) =split pivot xs in if x >= pivot then (sm,x:bg) else (x:sm,bg) ? split 4 [1,2,3,4,5,6,7] ([1, 2, 3],[4, 5, 6, 7]) quik2 [] = [] quik2 (x:xs) = (quik2 l) ++ (x : (quik2 h)) where (l,h) = split x xs

Cs536 Functional Programming 166/13/2015 Making Change Producing Change (exact number of nickels, dimes, quarters, pennies) for a given amount. Lots of solutions, how should we constrain the problem? –largest amount of "big" coins" change x = makechange x coins where coins = [("quarters",25), ("dimes",10), ("nickels",5), ("pennies",1)] makechange x [] = [] makechange x ((word,amt):m) = let count = x `div` amt left = x `mod` amt in if count==0 then makechange left m else (count,word):(makechange left m) ? change 72 [(2,"quarters"), (2,"dimes"), (2,"pennies")] (50 reductions, 198 cells)