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

0 PROGRAMMING IN HASKELL Chapter 10 - Declaring Types and Classes.
Chapter 11 Proof by Induction. Induction and Recursion Two sides of the same coin.  Induction usually starts with small things, and then generalizes.
String is a synonym for the type [Char].
0 LECTURE 5 LIST COMPREHENSIONS Graham Hutton University of Nottingham.
0 PROGRAMMING IN HASKELL Chapter 7 - Higher-Order Functions.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
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 PROGRAMMING IN HASKELL Chapter 11 - Interactive Programs, Declaring Types and Classes.
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) Modules.
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
0 PROGRAMMING IN HASKELL Chapter 7 - Defining Functions, List Comprehensions.
Chapter 9: Functional Programming in a Typed Language.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Types and Classes Dr. Hyunyoung Lee.
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.
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 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,
More Data Types CSCE 314 Spring CSCE 314 – Programming Studio Defining New Data Types Three ways to define types: 1.type – Define a synonym for.
Recursion Higher Order Functions CSCE 314 Spring 2016.
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.
1 PROGRAMMING IN HASKELL Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources) Type declarations.
Lecture 14: Advanced Topic: Functional Programming
Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x2 | x  {1...5}} The set {1,4,9,16,25}
Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x2 | x  {1...5}} The set {1,4,9,16,25}
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
String is a synonym for the type [Char].
Conditional Expressions
Recursion.
PROGRAMMING IN HASKELL
Types CSCE 314 Spring 2016.
ML: a quasi-functional language with strong typing
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
A lightening tour in 45 minutes
PROGRAMMING IN HASKELL
Haskell.
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Higher Order Functions
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Types and Classes 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
PROGRAMMING IN HASKELL
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 Type declarations and Modules Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)

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 recap and then see a few more…

Higher order functions Last time: Map: take something and apply it to everything in a list 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]]

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"

String is a synonym for the type [Char]. Type Declarations In Haskell, a new name for an existing type can be defined using a type declaration. type String = [Char] String is a synonym for the type [Char].

Type declarations can be used to make other types easier to read Type declarations can be used to make other types easier to read. For example, given type Pos = (Int,Int) we can define: origin :: Pos origin = (0,0) left :: Pos  Pos left (x,y) = (x-1,y)

Like function definitions, type declarations can also have parameters Like function definitions, type declarations can also have parameters. For example, given type Pair a = (a,a) we can define: mult :: Pair Int  Int mult (m,n) = m*n copy :: a  Pair a copy x = (x,x)

Type declarations can be nested: type Pos = (Int,Int) type Trans = Pos  Pos However, they cannot be recursive: type Tree = (Int,[Tree])

Bool is a new type, with two new values False and True. Data Declarations A completely new type can be defined by specifying its values using a data declaration. data Bool = False | True Bool is a new type, with two new values False and True.

Note: The two values False and True are called the constructors for the type Bool. Type and constructor names must begin with an upper-case letter. Data declarations are similar to context free grammars. The former specifies the values of a type, the latter the sentences of a language.

Values of new types can be used in the same ways as those of built in types. For example, given data Answer = Yes | No | Unknown we can define: answers :: [Answer] answers = [Yes,No,Unknown] flip :: Answer  Answer flip Yes = No flip No = Yes flip Unknown = Unknown

The constructors in a data declaration can also have parameters The constructors in a data declaration can also have parameters. For example, given data Shape = Circle Float | Rect Float Float we can define: square :: Float  Shape square n = Rect n n area :: Shape  Float area (Circle r) = pi * r^2 area (Rect x y) = x * y

Note: Shape has values of the form Circle r where r is a float, and Rect x y where x and y are floats. Circle and Rect can be viewed as functions that construct values of type Shape: Circle :: Float  Shape Rect :: Float  Float  Shape

Not surprisingly, data declarations themselves can also have parameters. For example, given data Maybe a = Nothing | Just a we can define: safediv :: Int  Int  Maybe Int safediv _ 0 = Nothing safediv m n = Just (m `div` n) safehead :: [a]  Maybe a safehead [] = Nothing safehead xs = Just (head xs)

Exercises: FIX – no show Write a function safeSecond which takes a list and returns its second element (assuming it has one). Note: you’ll need the following: data Maybe a = Nothing | Just a safehead :: [a]  Maybe a safehead [] = Nothing safehead xs = Just (head xs)

Recursive Types In Haskell, new types can be declared in terms of themselves. That is, types can be recursive. data Nat = Zero | Succ Nat Nat is a new type, with constructors Zero :: Nat and Succ :: Nat  Nat.

Note: A value of type Nat is either Zero, or of the form Succ n where n :: Nat. That is, Nat contains the following infinite sequence of values: Zero Succ Zero Succ (Succ Zero) 

represents the natural number We can think of values of type Nat as natural numbers, where Zero represents 0, and Succ represents the successor function 1+. For example, the value Succ (Succ (Succ Zero)) represents the natural number 1 + (1 + (1 + 0)) 3 =

Using recursion, it is easy to define functions that convert between values of type Nat and Int: nat2int :: Nat  Int nat2int Zero = 0 nat2int (Succ n) = 1 + nat2int n int2nat :: Int  Nat int2nat 0 = Zero int2nat (n+1) = Succ (int2nat n)

Two naturals can be added by converting them to integers, adding, and then converting back: add :: Nat  Nat  Nat add m n = int2nat (nat2int m + nat2int n) However, using recursion the function add can be defined without the need for conversions: add Zero n = n add (Succ m) n = Succ (add m n)

For example: add (Succ (Succ Zero)) (Succ Zero) Succ (add (Succ Zero) (Succ Zero)) = Succ (Succ (add Zero (Succ Zero)) = Succ (Succ (Succ Zero)) = Note: The recursive definition for add corresponds to the laws 0+n = n and (1+m)+n = 1+(m+n).

Arithmetic Expressions Consider a simple form of expressions built up from integers using addition and multiplication. 1 +  3 2

Using recursion, a suitable new type to represent such expressions can be declared by: data Expr = Val Int | Add Expr Expr | Mul Expr Expr For example, the expression on the previous slide would be represented as follows: Add (Val 1) (Mul (Val 2) (Val 3))

Using recursion, it is now easy to define functions that process expressions. For example: size :: Expr  Int size (Val n) = 1 size (Add x y) = size x + size y size (Mul x y) = size x + size y eval :: Expr  Int eval (Val n) = n eval (Add x y) = eval x + eval y eval (Mul x y) = eval x * eval y

The three constructors have types: Note: The three constructors have types: Val :: Int  Expr Add :: Expr  Expr  Expr Mul :: Expr  Expr  Expr Many functions on expressions can be defined by replacing the constructors by other functions using a suitable fold function. For example: eval = fold id (+) (*)

Binary Trees In computing, it is often useful to store data in a two-way branching structure or binary tree. 5 7 9 6 3 4 1

Using recursion, a suitable new type to represent such binary trees can be declared by: data Tree = Leaf Int | Node Tree Int Tree For example, the tree on the previous slide would be represented as follows: Node (Node (Leaf 1) 3 (Leaf 4)) 5 (Node (Leaf 6) 7 (Leaf 9))

We can now define a function that decides if a given integer occurs in a binary tree: occurs :: Int  Tree  Bool occurs m (Leaf n) = m==n occurs m (Node l n r) = m==n || occurs m l || occurs m r But… in the worst case, when the integer does not occur, this function traverses the entire tree.

Now consider the function flatten that returns the list of all the integers contained in a tree: flatten :: Tree  [Int] flatten (Leaf n) = [n] flatten (Node l n r) = flatten l ++ [n] ++ flatten r A tree is a search tree if it flattens to a list that is ordered. Our example tree is a search tree, as it flattens to the ordered list [1,3,4,5,6,7,9].

Search trees have the important property that when trying to find a value in a tree we can always decide which of the two sub-trees it may occur in: occurs m (Leaf n) = m==n occurs m (Node l n r) | m==n = True | m<n = occurs m l | m>n = occurs m r This new definition is more efficient, because it only traverses one path down the tree.

Exercise Node (Node (Leaf 1) 3 (Leaf 4)) 5 (Node (Leaf 6) 7 (Leaf 9)) A binary tree is complete if the two sub-trees of every node are of equal size. Define a function that decides if a binary tree is complete. data Tree = Leaf Int | Node Tree Int Tree occurs :: Int  Tree  Bool occurs m (Leaf n) = m==n occurs m (Node l n r) = m==n || occurs m l || occurs m r