PROGRAMMING IN HASKELL

Slides:



Advertisements
Similar presentations
Introduction A function is called higher-order if it takes a function as an argument or returns a function as a result. twice :: (a  a)  a  a twice.
Advertisements

A Third Look At ML 1. Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order.
0 LECTURE 5 LIST COMPREHENSIONS Graham Hutton University of Nottingham.
0 PROGRAMMING IN HASKELL Chapter 7 - Higher-Order Functions.
Higher-Order Functions Koen Lindström Claessen. What is a “Higher Order” Function? A function which takes another function as a parameter. Examples map.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
0 PROGRAMMING IN HASKELL Chapter 6 - Recursive Functions Most of this should be review for you.
0 PROGRAMMING IN HASKELL Chapter 6 - Recursive Functions.
0 PROGRAMMING IN HASKELL Chapter 3 - Types and Classes.
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.
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
0 PROGRAMMING IN HASKELL Chapter 7 - Defining Functions, List Comprehensions.
0 PROGRAMMING IN HASKELL Chapter 9 - Higher-Order Functions, Functional Parsers.
What is a Type? A type is a name for a collection of related values. For example, in Haskell the basic type Bool contains the two logical values: True.
0 Odds and Ends in Haskell: Folding, I/O, and Functors Adapted from material by Miran Lipovaca.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Higher-order Functions Dr. Hyunyoung Lee.
1 CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University.
0 INTRODUCTION TO FUNCTIONAL PROGRAMMING Graham Hutton University of Nottingham.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: More on Functions and List Comprehensions Dr. Hyunyoung Lee.
0 PROGRAMMING IN HASKELL Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources) Odds and Ends,
Recursion Higher Order Functions CSCE 314 Spring 2016.
Haskell Chapter 4. Recursion  Like other languages  Base case  Recursive call  Author programs a number of built-in functions as examples.
Haskell Chapter 5, Part II. Topics  Review/More Higher Order Functions  Lambda functions  Folds.
Lecture 16: Advanced Topic: Functional Programming CS5363 Compiler and Programming Languages.
1 PROGRAMMING IN HASKELL Lecture 2 Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)
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.
6-Jul-16 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
© M. Winter COSC 4P41 – Functional Programming Some functions id :: a -> a id x = x const :: a -> b -> a const k _ = k ($) :: (a -> b) -> a -> b.
Lecture 14: Advanced Topic: Functional Programming
Polymorphic Functions
What is a Parser? A parser is a program that analyses a piece of text to determine its syntactic structure  3 means 23+4.
Functional Programming
Conditional Expressions
Recursion.
PROGRAMMING IN HASKELL
Types CSCE 314 Spring 2016.
Theory of Computation Lecture 4: Programs and Computable Functions II
Functional Programming Lecture 12 - more higher order functions
PROGRAMMING IN HASKELL
A lightening tour in 45 minutes
Haskell Chapter 4.
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Higher-Order Functions
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Higher Order Functions
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
CSCE 314: Programming Languages Dr. Dylan Shell
Haskell Types, Classes, and Functions, Currying, and Polymorphism
Higher Order Functions
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
HIGHER ORDER FUNCTIONS
CSE 3302 Programming Languages
CSCE 314: Programming Languages Dr. Dylan Shell
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Functions and patterns
PROGRAMMING IN HASKELL
Lambda Expressions Cases
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Presentation transcript:

PROGRAMMING IN HASKELL Odds and Ends, and Type and Data definitions Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)

Higher order functions Remember that functions can also be inputs: applyTwice :: (a -> a) -> a -> a applyTwice f x = f (f x) After loading, we can use this with any function: ghci> applyTwice (+3) 10 16 ghci> applyTwice (++ " HAHA") "HEY" "HEY HAHA HAHA" ghci> applyTwice ("HAHA " ++) "HEY" "HAHA HAHA HEY" ghci> applyTwice (3:) [1] [3,3,1]

Useful functions: zipwith zipWith is a default in the prelude, but if we were coding it, it would look like this: zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] zipWith _ [] _ = [] zipWith _ _ [] = [] zipWith f (x:xs) (y:ys) = f x y : zipWith' f xs ys Look at declaration for a bit…

Useful functions: zipwith Using zipWith: ghci> zipWith (+) [4,2,5,6] [2,6,2,3] [6,8,7,9] ghci> zipWith max [6,3,2,1] [7,3,1,5] [7,3,2,5] ghci> zipWith (++) ["foo ", "bar ", "baz "] ["fighters", "hoppers", "aldrin"] ["foo fighters","bar hoppers","baz aldrin"] ghci> zipWith' (*) (replicate 5 2) [1..] [2,4,6,8,10] ghci> zipWith' (zipWith' (*)) [[1,2,3],[3,5,6],[2,3,4]] [[3,2,2],[3,4,5],[5,4,3]] [[3,4,6],[9,20,30],[10,12,12]]

Useful functions: map The function map applies a function across a list: map :: (a -> b) -> [a] -> [b] map _ [] = [] map f (x:xs) = f x : map f xs ghci> map (+3) [1,5,3,1,6] [4,8,6,4,9] ghci> map (++ "!") ["BIFF", "BANG", "POW"] ["BIFF!","BANG!","POW!"] ghci> map (replicate 3) [3..6] [[3,3,3],[4,4,4],[5,5,5],[6,6,6]] ghci> map (map (^2)) [[1,2],[3,4,5,6],[7,8]] [[1,4],[9,16,25,36],[49,64]]

Useful functions: filter The function fliter: filter :: (a -> Bool) -> [a] -> [a] filter _ [] = [] filter p (x:xs) | p x = x : filter p xs | otherwise = filter p xs ghci> filter (>3) [1,5,3,2,1,6,4,3,2,1] [5,6,4] ghci> filter (==3) [1,2,3,4,5] [3] ghci> filter even [1..10] [2,4,6,8,10]

Using filter: quicksort! quicksort :: (Ord a) => [a] -> [a] quicksort [] = [] quicksort (x:xs) = let smallerSorted = quicksort (filter (<=x) xs) biggerSorted = quicksort (filter (>x) xs) in smallerSorted ++ [x] ++ biggerSorted (Also using let clause, which temporarily binds a function in the local context. The function actually evaluates to whatever “in” is.)

Exercise Write a function myZip :: [a] -> [b] -> [(a, b)] which zips two lists together: myZip [1,2,3] "abc" = [(1, 'a'), (2, 'b'), (3, 'c')] (If one list is smaller, just go ahead and stop whenever one of them ends.) Hint: I’d do this with recursion! Just don’t use the included function zip, since that is cheating.

Conditional Expressions As in most programming languages, functions can be defined using conditional expressions. abs :: Int  Int abs n = if n  0 then n else -n abs takes an integer n and returns n if it is non-negative and -n otherwise.

Conditional expressions can be nested: signum :: Int  Int signum n = if n < 0 then -1 else if n == 0 then 0 else 1 Note: In Haskell, conditional expressions must always have an else branch, which avoids any possible ambiguity issues.

As previously, but using guarded equations. As an alternative to conditionals, functions can also be defined using guarded equations. abs n | n  0 = n | otherwise = -n As previously, but using guarded equations.

Guarded equations can be used to make definitions involving multiple conditions easier to read: signum n | n < 0 = -1 | n == 0 = 0 | otherwise = 1 Note: The catch all condition otherwise is defined in the prelude by otherwise = True.

not maps False to True, and True to False. Pattern Matching Many functions have a particularly clear definition using pattern matching on their arguments. not :: Bool  Bool not False = True not True = False not maps False to True, and True to False.

can be defined more compactly by Functions can often be defined in many different ways using pattern matching. For example (&&) :: Bool  Bool  Bool True && True = True True && False = False False && True = False False && False = False can be defined more compactly by True && True = True _ && _ = False

However, the following definition is more efficient, because it avoids evaluating the second argument if the first argument is False: True && b = b False && _ = False Note: The underscore symbol _ is a wildcard pattern that matches any argument value.

Patterns are matched in order Patterns are matched in order. For example, the following definition always returns False: _ && _ = False True && True = True Patterns may not repeat variables. For example, the following definition gives an error: b && b = b _ && _ = False

List Patterns Internally, every non-empty list is constructed by repeated use of an operator (:) called “cons” that adds an element to the start of a list. [1,2,3,4] Means 1:(2:(3:(4:[]))).

Functions on lists can be defined using x:xs patterns. head :: [a]  a head (x:_) = x tail :: [a]  [a] tail (_:xs) = xs head and tail map any non-empty list to its first and remaining elements.

x:xs patterns only match non-empty lists: Note: x:xs patterns only match non-empty lists: > head [] Error x:xs patterns must be parenthesised, because application has priority over (:). For example, the following definition gives an error: head x:_ = x

Lambda Expressions Functions can be constructed without naming the functions by using lambda expressions. x  x+x the nameless function that takes a number x and returns the result x+x.

Note: The symbol  is the Greek letter lambda, and is typed at the keyboard as a backslash \. In mathematics, nameless functions are usually denoted using the  symbol, as in x  x+x. In Haskell, the use of the  symbol for nameless functions comes from the lambda calculus, the theory of functions on which Haskell is based.

is more naturally defined by Lambda expressions are useful when defining functions that return functions as results. For example: const :: a  b  a const x _ = x is more naturally defined by const :: a  (b  a) const x = _  x

Lambda expressions can be used to avoid naming functions that are only referenced once. For example: odds n = map f [0..n-1] where f x = x*2 + 1 can be simplified to odds n = map (x  x*2 + 1) [0..n-1]

Sections An operator written between its two arguments can be converted into a curried function written before its two arguments by using parentheses. For example: > 1+2 3 > (+) 1 2

This convention also allows one of the arguments of the operator to be included in the parentheses. For example: > (1+) 2 3 > (+2) 1 In general, if  is an operator then functions of the form (), (x) and (y) are called sections.

Why Are Sections Useful? Useful functions can sometimes be constructed in a simple way using sections. For example: - successor function - reciprocation function - doubling function - halving function (1+) (*2) (/2) (1/)

Exercise Consider a function safetail that behaves in the same way as tail, except that safetail maps the empty list to the empty list, whereas tail gives an error in this case. Define safetail using: (a) a conditional expression; (b) guarded equations; (c) pattern matching. Hint: the library function null :: [a]  Bool can be used to test if a list is empty.

Higher order functions Last time we started discussing higher order functions, or functions that take other functions are input. These are heavily useful, and are one of the strengths of Haskell! Let’s see a few more…

The Foldr Function A number of functions on lists can be defined using the following simple pattern of recursion: f [] = v f (x:xs) = x  f xs f maps the empty list to some value v, and any non-empty list to some function  applied to its head and f of its tail.

v = 0 v = 1 v = True For example: sum [] = 0 sum (x:xs) = x + sum xs  = + product [] = 1 product (x:xs) = x * product xs v = 1  = * and [] = True and (x:xs) = x && and xs v = True  = &&

The higher-order library function foldr (fold right) encapsulates this simple pattern of recursion, with the function  and the value v as arguments. For example: sum = foldr (+) 0 product = foldr (*) 1 or = foldr (||) False and = foldr (&&) True

Foldr itself can be defined using recursion: foldr :: (a  b  b)  b  [a]  b foldr f v [] = v foldr f v (x:xs) = f x (foldr f v xs) However, it is best to think of foldr non-recursively, as simultaneously replacing each (:) in a list by a given function, and [] by a given value.

For example: = = = = Replace each (:) by (+) and [] by 0. sum [1,2,3] foldr (+) 0 [1,2,3] = foldr (+) 0 (1:(2:(3:[]))) = 1+(2+(3+0)) = 6 = Replace each (:) by (+) and [] by 0.

For example: = = = = Replace each (:) by (*) and [] by 1. product [1,2,3] foldr (*) 1 [1,2,3] = foldr (*) 1 (1:(2:(3:[]))) = 1*(2*(3*1)) = 6 = Replace each (:) by (*) and [] by 1.

Other Foldr Examples Even though foldr encapsulates a simple pattern of recursion, it can be used to define many more functions than might first be expected. Recall the length function: length :: [a]  Int length [] = 0 length (_:xs) = 1 + length xs

Replace each (:) by _ n  1+n and [] by 0. For example: length [1,2,3] length (1:(2:(3:[]))) = 1+(1+(1+0)) = 3 = Replace each (:) by _ n  1+n and [] by 0. Hence, we have: length = foldr (_ n  1+n) 0

Replace each (:) by x xs  xs ++ [x] and [] by []. Now recall the reverse function: reverse [] = [] reverse (x:xs) = reverse xs ++ [x] For example: Replace each (:) by x xs  xs ++ [x] and [] by []. reverse [1,2,3] reverse (1:(2:(3:[]))) = (([] ++ [3]) ++ [2]) ++ [1] = [3,2,1] =

Replace each (:) by (:) and [] by ys. Hence, we have: reverse = foldr (x xs  xs ++ [x]) [] Finally, we note that the append function (++) has a particularly compact definition using foldr: Replace each (:) by (:) and [] by ys. (++ ys) = foldr (:) ys

Why Is Foldr Useful? Some recursive functions on lists, such as sum, are simpler to define using foldr. Properties of functions defined using foldr can be proved using algebraic properties of foldr, such as fusion and the banana split rule. Advanced program optimizations can be simpler if foldr is used in place of explicit recursion.

Other Library Functions The library function (.) returns the composition of two functions as a single function. (.) :: (b  c)  (a  b)  (a  c) f . g = x  f (g x) For example: odd :: Int  Bool odd = not . even

The library function all decides if every element of a list satisfies a given predicate. all :: (a  Bool)  [a]  Bool all p xs = and [p x | x  xs] For example: > all even [2,4,6,8,10] True

Dually, the library function any decides if at least one element of a list satisfies a predicate. any :: (a  Bool)  [a]  Bool any p xs = or [p x | x  xs] For example: > any isSpace "abc def" True

The library function takeWhile selects elements from a list while a predicate holds of all the elements. takeWhile :: (a  Bool)  [a]  [a] takeWhile p [] = [] takeWhile p (x:xs) | p x = x : takeWhile p xs | otherwise = [] For example: > takeWhile isAlpha "abc def" "abc"

Dually, the function dropWhile removes elements while a predicate holds of all the elements. dropWhile :: (a  Bool)  [a]  [a] dropWhile p [] = [] dropWhile p (x:xs) | p x = dropWhile p xs | otherwise = x:xs For example: > dropWhile isSpace " abc" "abc"