© M. Winter COSC 4P41 – Functional Programming 6.16.1 Enumerated types data Temp = Cold | Hot data Season= Spring | Summer | Autumn | Winter weather ::

Slides:



Advertisements
Similar presentations
Functional Programming Lecture 10 - type checking.
Advertisements

Functional Programming Lecture 15 - Case Study: Huffman Codes.
Haskell user defined types data Temp = Cold|Hot|Warm deriving (Show,Eq, Ord, Enum) -- to enable printing to screen -- comparing for equality -- comparison.
Modern Programming Languages, 2nd ed.
Haskell Chapter 7. Topics  Defining data types  Exporting types  Type parameters  Derived instances  Type synonyms  Either  Type classes  Not.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
© M. Winter COSC 4P41 – Functional Programming Testing vs Proving Testing –uses a set of “typical” examples, –symbolic testing, –may find errors,
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
0 PROGRAMMING IN HASKELL Chapter 10 - Declaring Types and Classes.
String is a synonym for the type [Char].
Binary Trees CSC 220. Your Observations (so far data structures) Array –Unordered Add, delete, search –Ordered Linked List –??
Greedy Algorithms Greed is good. (Some of the time)
© M. Winter COSC 4P41 – Functional Programming Abstract data types (ADTs) An ADT is a data type together with some functions to manipulate elements.
Com Functional Programming Algebraic Data Types Marian Gheorghe Lecture 12 Module homepage Mole & ©University of.
Using Types Slides thanks to Mark Jones. 2 Expressions Have Types: The type of an expression tells you what kind of value you might expect to see if you.
Cse536 Functional Programming 1 6/12/2015 Lecture #11, Nov. 01, 2004 Special Guest lecture by Tom Harke Today’s Topics –The Haskell Class system –Instance.
Comp 205: Comparative Programming Languages User-Defined Types Enumerated types Parameterised types Recursive types Lecture notes, exercises, etc., can.
Advanced Programming Handout 9 Qualified Types (SOE Chapter 12)
Advanced Programming Andrew Black and Tim Sheard Lecture 4 Intro to Haskell.
0 PROGRAMMING IN HASKELL Chapter 3 - Types and Classes.
Using Types Slides thanks to Mark Jones. 2 Expressions Have Types: The type of an expression tells you what kind of value you might expect to see if you.
CS 46B: Introduction to Data Structures July 30 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
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 COMP313A Programming Languages Functional Programming (7)
Data Structures Arrays both single and multiple dimensions Stacks Queues Trees Linked Lists.
0 PROGRAMMING IN HASKELL Chapter 11 - Interactive Programs, Declaring Types and Classes.
PrasadCS7761 Haskell Data Types/ADT/Modules Type/Class Hierarchy Lazy Functional Language.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
1 Huffman Codes Drozdek Chapter Objectives You will be able to Construct an optimal variable bit length code for an alphabet with known probability.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Types and Classes Dr. Hyunyoung Lee.
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
11/1/20151 GC16/3011 Functional Programming Lecture 5 Miranda patterns, functions, recursion and lists.
Modeling with Haskell Scientific Seminar 03/04 Gerhard Navratil.
1 Functional Programming Lecture 6 - Algebraic Data Types.
A Second Look At ML 1. Outline Patterns Local variable definitions A sorting example 2.
Overview of the Haskell 98 Programming Language
© M. Winter COSC 4P41 – Functional Programming Programming with actions Why is I/O an issue? I/O is a kind of side-effect. Example: Suppose there.
© M. Winter COSC 4P41 – Functional Programming Modules in Haskell Using modules to structure a large program has a number of advantages: Parts of.
1 CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University.
Recursion on Lists Lecture 5, Programmeringsteknik del A.
Chapter SevenModern Programming Languages1 A Second Look At ML.
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.
Functional Programming Lecture 16 - Case Study: Huffman Codes con’t.
Defining Classes Modules and ADTs CSCE 314 Spring 2016.
An introduction to functional programming using Haskell CENG242 –Recitation 1.
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.
© 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.
Chapter 11 Sorting Acknowledgement: These slides are adapted from slides provided with Data Structures and Algorithms in C++, Goodrich, Tamassia and Mount.
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
String is a synonym for the type [Char].
PROGRAMMING IN HASKELL
Types CSCE 314 Spring 2016.
Huffman Codes ASCII is a fixed length 7 bit code that uses the same number of bits to define each character regardless of how frequently it occurs. Huffman.
Theory of Computation Lecture 4: Programs and Computable Functions II
Representing Sets (2.3.3) Huffman Encoding Trees (2.3.4)
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Types and Classes in Haskell
PROGRAMMING IN HASKELL
Haskell Types, Classes, and Functions, Currying, and Polymorphism
CS 457/557: Functional Languages Folds
Records and Type Classes
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Theory of Computation Lecture 4: Programs and Computable Functions II
PROGRAMMING IN HASKELL
Records and Type Classes
Presentation transcript:

© M. Winter COSC 4P41 – Functional Programming Enumerated types data Temp = Cold | Hot data Season= Spring | Summer | Autumn | Winter weather :: Season -> Temp weather Summer = Hot weather _ = Cold Examples from Prelude.hs: data Bool = False | True data Ordering= LT | EQ | GT

© M. Winter COSC 4P41 – Functional Programming Product types type Name= String type Age= Int data People= Person Name Age Examples values of type People: Person ”Electric Aunt Jemima” 77 Person ”Ronnie” 14 Person :: Name -> Age -> People

© M. Winter COSC 4P41 – Functional Programming Algebraic types vs Type synonyms Type synonyms: type People = (Name,Age) Advantages of algebraic types Each object of the type carries an explicit label of the purpose of the element. It is not possible accidentally to treat an arbitrary pair consisting of a string and a number as a person. The type will appear in any error messages due to mis-typing. The principle of information hiding can be applied (in connection with modules). Advantages of type synonyms: The elements are more compact, and so definitions will be shorter. Using a pair allows us to reuse many polymorphic functions such as fst and snd.

© M. Winter COSC 4P41 – Functional Programming Alternatives data Shape= Circle Float | Rectangle Float Float isRound :: Shape -> Bool isRound (Circle _)= True isRound (Rectangle _ _) = False area :: Shape -> Float area (Circle r)= pi*r*r area (Rectangle h w)= h*w Circle :: Float -> Shape Rectangle :: Float -> Float -> Shape

© M. Winter COSC 4P41 – Functional Programming Algebraic types General form of algebraic type definitions data Typename = Con 1 t 11 … t 1k 1 | Con 2 t 21 … t 2k 2 … | Con n t n1 … t nk n This defines constructor functions with the following types Con i :: t i1 -> … -> t ik i -> Typename

© M. Winter COSC 4P41 – Functional Programming Derived instances For a new algebraic type Haskell can derive default implementations for several overloaded functions. Examples: data Season= Spring | Summer | Autumn | Winter deriving (Eq,Ord,Enum,Show,Read) data Shape= Circle Float | Rectangle Float Float deriving (Eq,Ord,Show,Read) We cannot expect that elements of Shape can be enumerated (being in Enum can only be derived for enumerated types). The membership relations for Shape can be derived because the type of the component, i.e. Float, is already an instance of those classes.

© M. Winter COSC 4P41 – Functional Programming Recursive algebraic types data IntTree = Empty | Node Int IntTree IntTree sumTree :: IntTree -> Int sumTree Empty = 0 sumTree (Node n t1 t2)= n + sumTree t1 + sumTree t2 depth :: IntTree -> Int depth Empty= 0 depth (Node n t1 t2)= 1 + max (depth t1) (depth t2) occurs :: IntTree -> Int -> Int occurs Empty x= 0 occurs (Node n t1 t2) x | n==x= 1 + occurs t1 x + occurs t2 x | otherwise= occurs t1 x + occurs t2 x inTree :: Int -> IntTree -> Bool inTree x Empty = False inTree x (Node n t1 t2) = n==x || x `inTree` t1 || x `inTree` t2

© M. Winter COSC 4P41 – Functional Programming Recursive algebraic types (cont’d) foldIntTree :: (Int -> a -> a -> a) -> a -> IntTree -> a foldIntTree f x Empty = x foldIntTree f x (Node n t1 t2) = f n (foldIntTree f x t1) (foldIntTree f x t2) sumTree= foldIntTree (\n m p -> n + m + p) 0 depth= foldIntTree (\_ m p -> 1 + max m p) 0 occurs t x= foldIntTree (\n m p -> (if n==x then 1 else 0) + m + p) 0 t inTree x = foldIntTree (\n b1 b2 -> n==x || b1 || b2) False Mutual recursion data Person = Adult Name Address Biog | Child Name data Biog= Parent String [Person] | NonParent String

© M. Winter COSC 4P41 – Functional Programming Example data Expr= Lit Int | Expr :+: Expr | Expr :-: Expr deriving (Eq) instance Show Expr where show (Lit n) = show n show (e1 :+: e2)= "(" ++ show e1 ++ "+" ++ show e2 ++")" show (e1 :-: e2)= "(" ++ show e1 ++ "-" ++ show e2 ++")" eval :: Expr -> Int eval (Lit n)= n eval (e1 :+: e2)= eval e1 + eval e2 eval (e1 :-: e2)= eval e1 - eval e2

© M. Winter COSC 4P41 – Functional Programming Polymorphic algebraic types data Tree a= Empty | Node a (Tree a) (Tree a) foldTree :: (a -> b -> b -> b) -> b -> Tree a -> b foldTree f x Empty = x foldTree f x (Node y t1 t2) = f y (foldTree f x t1) (foldTree f x t2) sumTree :: Tree Int -> Int sumTree= foldTree (\n m p -> n + m + p) 0 depth :: Tree a -> Int depth= foldTree (\_ m p -> 1 + max m p) 0 occurs :: Eq a => a -> Tree a -> Int occurs x= foldTree (\y m p -> (if x==y then 1 else 0) + m + p) 0 inTree :: Eq a => a -> Tree a -> Bool inTree x = foldTree (\y b1 b2 -> x==y || b1 || b2) False mapTree :: (a -> b) -> Tree a -> Tree b mapTree f Empty= Empty mapTree f (Node x t1 t2)= Node (f x) (mapTree f t1) (mapTree f t2)

© M. Winter COSC 4P41 – Functional Programming Union type data Either a b = Left a | Right b deriving (Eq, Ord, Read, Show) either :: (a -> c) -> (b -> c) -> Either a b -> c either l r (Left x) = l x either l r (Right y) = r y Either a bc a b l r

© M. Winter COSC 4P41 – Functional Programming Error type errDiv :: Int -> Int -> Int errDiv n m | m /= 0= n `div` m | otherwise= error ”Division by zero” Here, a division by 0 results in an error message and the program is terminated. data Maybe a = Nothing | Just a deriving (Eq, Ord, Read, Show) errDiv :: Int -> Int -> Maybe Int errDiv n m | m /= 0= Just (n `div` m) | otherwise= Nothing

© M. Winter COSC 4P41 – Functional Programming Error type (cont’d) mapMaybe :: (a -> b) -> Maybe a -> Maybe b mapMaybe g Nothing = Nothing mapMaybe g (Just x) = g x Maybe a a g Maybe b b

© M. Winter COSC 4P41 – Functional Programming Error type (cont’d) maybe :: b -> (a -> b) -> Maybe a -> b maybe n f Nothing = n maybe n f (Just x) = f x Maybe a a f b n

© M. Winter COSC 4P41 – Functional Programming Case study: Huffman codes Trees can be used to code and decode messages. Consider the tree: code b = RL a bt

© M. Winter COSC 4P41 – Functional Programming Huffman codes (cont’d) Decoding: RLLRR decode RLLRR = bat a b t a b t a b t a b t a b t a b t a b t a b t

© M. Winter COSC 4P41 – Functional Programming Huffman codes (cont’d) code battat = RLLRRRRLRR (10 bits) code battat = RRRLLLRLL (9 bits) t ab

© M. Winter COSC 4P41 – Functional Programming Types.lhs The types used in the Huffman coding example. (c) Simon Thompson, 1995, 1998 The interface to the module Types is written out explicitly here, after the module name. > module Types ( Tree(Leaf,Node), Bit(L,R), > HCode, Table ) where Trees to represent the relative frequencies of characters and therefore the Huffman codes. > data Tree = Leaf Char Int | Node Int Tree Tree The types of bits, Huffman codes and tables of Huffman codes. > data Bit = L | R deriving (Eq,Show) > type HCode = [Bit] > type Table = [ (Char,HCode) ]

© M. Winter COSC 4P41 – Functional Programming Frequency.lhs Calculating the frequencies of words in a text, used in Huffman coding. (c) Simon Thompson, 1995, > module Frequency ( frequency ) where Calculate the frequencies of characters in a list. This is done by sorting, then counting the number of repetitions. The counting is made part of the merge operation in a merge sort. > frequency :: [Char] -> [ (Char,Int) ] > frequency > = mergeSort freqMerge. mergeSort alphaMerge. map start > where > start ch = (ch,1)

© M. Winter COSC 4P41 – Functional Programming Merge sort parametrised on the merge operation. This is more general than parametrising on the ordering operation, since it permits amalgamation of elements with equal keys for instance. > mergeSort :: ([a]->[a]->[a]) -> [a] -> [a] > mergeSort merge xs > | length xs < 2 = xs > | otherwise > = merge (mergeSort merge first) > (mergeSort merge second) > where > first = take half xs > second = drop half xs > half = (length xs) `div` 2 Order on first entry of pairs, with accumulation of the numeric entries when equal first entry. > alphaMerge :: [(Char,Int)] -> [(Char,Int)] -> [(Char,Int)] > alphaMerge xs [] = xs > alphaMerge [] ys = ys > alphaMerge ((p,n):xs) ((q,m):ys) > | (p==q) = (p,n+m) : alphaMerge xs ys > | (p<q) = (p,n) : alphaMerge xs ((q,m):ys) > | otherwise = (q,m) : alphaMerge ((p,n):xs) ys

© M. Winter COSC 4P41 – Functional Programming Lexicographic ordering, second field more significant. > freqMerge :: [(Char,Int)] -> [(Char,Int)] -> [(Char,Int)] > freqMerge xs [] = xs > freqMerge [] ys = ys > freqMerge ((p,n):xs) ((q,m):ys) > | (n<m || (n==m && p<q)) > = (p,n) : freqMerge xs ((q,m):ys) > | otherwise > = (q,m) : freqMerge ((p,n):xs) ys

© M. Winter COSC 4P41 – Functional Programming makeTree.lhs Turn a frequency table into a Huffman tree (c) Simon Thompson, > module MakeTree ( makeTree ) where > import Types ( Tree(Leaf,Node), Bit(L,R), HCode, Table ) Convert the trees to a list, then amalgamate into a single tree. > makeTree :: [ (Char,Int) ] -> Tree > makeTree = makeCodes. toTreeList Huffman codes are created bottom up: look for the least two frequent letters, make these a new "isAlpha" (i.e. tree) and repeat until one tree formed. The function toTreeList makes the initial data structure. > toTreeList :: [ (Char,Int) ] -> [ Tree ] > toTreeList = map (uncurry Leaf)

© M. Winter COSC 4P41 – Functional Programming The value of a tree. > value :: Tree -> Int > value (Leaf _ n) = n > value (Node n _ _) = n Pair two trees. > pair :: Tree -> Tree -> Tree > pair t1 t2 = Node (v1+v2) t1 t2 > where > v1 = value t1 > v2 = value t2 Insert a tree in a list of trees sorted by ascending value. > insTree :: Tree -> [Tree] -> [Tree] > insTree t [] = [t] > insTree t (t1:ts) > | (value t <= value t1) = t:t1:ts > | otherwise = t1 : insTree t ts

© M. Winter COSC 4P41 – Functional Programming Amalgamate the front two elements of the list of trees. > amalgamate :: [ Tree ] -> [ Tree ] > amalgamate ( t1 : t2 : ts ) > = insTree (pair t1 t2) ts Make codes: amalgamate the whole list. > makeCodes :: [Tree] -> Tree > makeCodes [t] = t > makeCodes ts = makeCodes (amalgamate ts)

© M. Winter COSC 4P41 – Functional Programming codeTable.lhs Converting a Huffman tree to a ord table. (c) Simon Thompson, 1995, > module CodeTable ( codeTable ) where > import Types ( Tree(Leaf,Node), Bit(L,R), HCode, Table ) Making a table from a Huffman tree. > codeTable :: Tree -> Table > codeTable = convert [] Auxiliary function used in conversion to a table. The first argument is the HCode which codes the path in the tree to the current Node, and so codeTable is initialised with an empty such sequence. > convert :: HCode -> Tree -> Table > convert cd (Leaf c n) = [(c,cd)] > convert cd (Node n t1 t2) > = (convert (cd++[L]) t1) ++ (convert (cd++[R]) t2)

© M. Winter COSC 4P41 – Functional Programming Show functions ^^^^^^^^^^^^^^ Show a tree, using indentation to show structure. > showTree :: Tree -> String > showTree t = showTreeIndent 0 t The auxiliary function showTreeIndent has a second, current level of indentation, as a parameter. > showTreeIndent :: Int -> Tree -> String > showTreeIndent m (Leaf c n) > = spaces m ++ show c ++ " " ++ show n ++ "\n" > showTreeIndent m (Node n t1 t2) > = showTreeIndent (m+4) t1 ++ > spaces m ++ "[" ++ show n ++ "]" ++ "\n" ++ > showTreeIndent (m+4) t2 A String of n spaces. > spaces :: Int -> String > spaces n = replicate n ' '

© M. Winter COSC 4P41 – Functional Programming To show a sequence of Bits. > showCode :: HCode -> String > showCode = map conv > where > conv R = 'R' > conv L = 'L' To show a table of codes. >showTable :: Table -> String > showTable > = concat. map showPair > where > showPair (ch,co) = [ch] ++ " " ++ showCode co ++ "\n"

© M. Winter COSC 4P41 – Functional Programming Coding.lhs Huffman coding in Haskell. The top-level functions for coding and decoding. (c) Simon Thompson, > module Coding ( codeMessage, decodeMessage ) where > import Types ( Tree(Leaf,Node), Bit(L,R), HCode, Table ) Code a message according to a table of codes. > codeMessage :: Table -> [Char] -> HCode > codeMessage tbl = concat. map (lookupTable tbl) lookupTable looks up the meaning of an individual char in a Table. > lookupTable :: Table -> Char -> HCode > lookupTable [] c = error "lookupTable" > lookupTable ((ch,n):tb) c > | (ch==c) = n > | otherwise = lookupTable tb c

© M. Winter COSC 4P41 – Functional Programming Decode a message according to a tree. The first tree arguent is constant, being the tree of codes; the second represents the current position in the tree relative to the (partial) HCode read so far. > decodeMessage :: Tree -> HCode -> String > decodeMessage tr > = decodeByt tr > where > > decodeByt (Node n t1 t2) (L:rest) > = decodeByt t1 rest > > decodeByt (Node n t1 t2) (R:rest) > = decodeByt t2 rest > > decodeByt (Leaf c n) rest > = c : decodeByt tr rest > > decodeByt t [] = []

© M. Winter COSC 4P41 – Functional Programming MakeCode.lhs Huffman coding in Haskell. (c) Simon Thompson, 1995, > module MakeCode ( codes, codeTable ) where > import Types > import Frequency ( frequency ) > import MakeTree ( makeTree ) > import CodeTable ( codeTable ) Putting together frequency calculation and tree conversion > codes :: [Char] -> Tree > codes = makeTree. frequency

© M. Winter COSC 4P41 – Functional Programming Main.lhs The main module of the Huffman example (c) Simon Thompson, 1995,1998. The main module of the Huffman example > module Main (main) where > import Types ( Tree(Leaf,Node), Bit(L,R), HCode, Table ) > import Coding ( codeMessage, decodeMessage ) > import MakeCode ( codes, codeTable ) > main = print decoded Examples ^^^^^^^^ The coding table generated from the text "there is a green hill". >tableEx :: Table > tableEx = codeTable (codes "there is a green hill")

© M. Winter COSC 4P41 – Functional Programming The Huffman tree generated from the text "there is a green hill", from which tableEx is produced by applying codeTable. >treeEx :: Tree > treeEx = codes "there is a green hill" A message to be coded. >message :: String > message = "there are green hills here" The message in code. >coded :: HCode > coded = codeMessage tableEx message The coded message decoded. >decoded :: String > decoded = decodeMessage treeEx coded