© M. Winter COSC 4P41 – Functional Programming 5.15.1 Modules in Haskell Using modules to structure a large program has a number of advantages: Parts of.

Slides:



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

0 PROGRAMMING IN HASKELL Chapter 5 - List Comprehensions.
Haskell Chapter 7. Topics  Defining data types  Exporting types  Type parameters  Derived instances  Type synonyms  Either  Type classes  Not.
© M. Winter COSC 4P41 – Functional Programming Abstract data types (ADTs) An ADT is a data type together with some functions to manipulate elements.
© M. Winter COSC 4P41 – Functional Programming Patterns of computation over lists Applying to all – mapping map :: (a -> b) -> [a] -> [b] map f.
COMP150PLD Thanks to Simon Peyton Jones for some of these slides. Reading: “Concepts in Programming Languages”, New Chapter 7, Type Classes; “How to make.
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.
5. Types and Polymorphism. © O. Nierstrasz PS — Type Systems 5.2 Roadmap  Static and Dynamic Types  Type Completeness  Types in Haskell  Monomorphic.
0 PROGRAMMING IN HASKELL Chapter 5 - List Comprehensions.
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.
Chapter 9 More About Higher-Order Functions. Currying Recall the function: simple n a b = n * (a+b) Note that: simple n a b is really (((simple n) a)
A Lightning Tour of Haskell Lecture 1, Designing and Using Combinators John Hughes.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
Advanced Programming Handout 9 Qualified Types (SOE Chapter 12)
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.
Chapter 12 Qualified Types. Motivation  What should the principal type of (+) be? Int -> Int -> Int-- too specific a -> a -> a-- too general  It seems.
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,
Comp 205: Comparative Programming Languages Functional Programming Languages: More Lists Recursive definitions List comprehensions Lecture notes, exercises,
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.
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)
© M. Winter COSC 4P41 – Functional Programming Enumerated types data Temp = Cold | Hot data Season= Spring | Summer | Autumn | Winter weather ::
PrasadCS7761 Haskell Data Types/ADT/Modules Type/Class Hierarchy Lazy Functional Language.
Operators, Functions and Modules1 Pattern Matching & Recursion.
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
0 PROGRAMMING IN HASKELL Chapter 7 - Defining Functions, List Comprehensions.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Types and Classes Dr. Hyunyoung Lee.
1-Nov-15 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
Overview of the Haskell 98 Programming Language
CS5205Haskell1 CS5205: Foundations in Programming Languages FP with Haskell A pure lazy functional language that embodies many innovative ideas in language.
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.
1 CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
CS321 Functional Programming 2 © JAS CS321 Functional Programming 2 Dr John A Sharp 10 credits Tuesday 10amRobert Recorde Room Thursday 11amRobert.
Do-it-yourself dictionaries in Haskell1 Ingmar Brouns & Lukas Spee.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
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.
Defining Classes Modules and ADTs CSCE 314 Spring 2016.
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.
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
Haskell Chapter 7.
PROGRAMMING IN HASKELL
Types CSCE 314 Spring 2016.
Haskell Chapter 2.
MPCS 51400: Functional Programming
Functions and patterns
A lightening tour in 45 minutes
PROGRAMMING IN HASKELL
CSE 3302 Programming Languages
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Type & Typeclass Syntax in function
Types and Classes in Haskell
CSCE 314: Programming Languages Dr. Dylan Shell
Haskell Types, Classes, and Functions, Currying, and Polymorphism
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Records and Type Classes
Functions and patterns
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Records and Type Classes
Presentation transcript:

© M. Winter COSC 4P41 – Functional Programming Modules in Haskell Using modules to structure a large program has a number of advantages: Parts of the system can be built separately from each other. Parts of the system can be compiled separately. Libraries of components can be reused, by importing the appropriate module containing them. module Ant where type Ants = … antEater x = … The convention for file names is that a module Ant resides in the Haskell file Ant.hs or Ant.lhs.

© M. Winter COSC 4P41 – Functional Programming Importing a module module Bee where import Ant beeKeeper = … Importing the module Ant means that the visible definitions from the module can be used in Bee. By default the visible definitions in a module are those which appear in the module itself. module Cow where import Bee The definitions of Ant are not visible in Cow.

© M. Winter COSC 4P41 – Functional Programming Export control We can control what is exported by following the name of the module with a list of what is to be exported. module Bee (beeKeeper, Ants, antEater) where … module Bee (beeKeeper, module Ant) where … module Fish where type Fish = (String,Size) module Fish (Fish(..),…) where newtype Fish = F (String,Size) module Fish (Fish,…) where newtype Fish = F (String,Size)

© M. Winter COSC 4P41 – Functional Programming Import control Examples: import Ant (Ants) import Ant hiding (antEater) module Bear where import qualified Ant antEater x = … Ant.antEater x … import Insect as Ant import Prelude hiding (words) import qualified Prelude

© M. Winter COSC 4P41 – Functional Programming Overloading and type classes A polymorphic function such as length has a single definition which works over all its types. length:: [a] -> Int length = foldl' (\n _ -> n + 1) 0 An overloaded function like equality ( == ), + and show can be used at a variety of types, but with different definitions being used at different types.

© M. Winter COSC 4P41 – Functional Programming Why overloading? elemBool :: Bool -> [Bool] -> Bool elemBool x [] = False elemBool x (y:ys)= (x == Bool y) || elemBool x ys elemInt :: Int -> [Int] -> Bool elemInt x [] = False elemInt x (y:ys)= (x == Int y) || elemInt x ys Generalization may lead to the definition: elemGen :: (a -> a -> Bool) -> a -> [a] -> Bool elemGen p x []= False elemGen p x (y:ys)= p x y || elemGen x ys but this is too general in a sense, because it can be used with any parameter of type a -> a -> Bool rather than just an equality check.

© M. Winter COSC 4P41 – Functional Programming Why overloading? (cont’d) Generalization in the following way will not work. The definition elem :: a -> [a] -> Bool elem x []= False elem x (y:ys)= (x == y) || elem x ys will cause an error No instance for (Eq a) arising from a use of `==' In the first argument of `(||)', namely `x == y' In the expression: x == y || elem x ys In an equation for `elem`: elem x (y : ys) = x == y || elem x ys because this definition requires that (==) :: a -> a -> Bool is already defined.

© M. Winter COSC 4P41 – Functional Programming Classes A type class or simply a class defines a collection of types over which specific functions are defined. class Eq a where (==) :: a -> a -> Bool Members of a class are called instances. Built-in instances of Eq include the base types Int, Float, Bool, Char, tuples and lists built from types which are themselves instances of Eq, e.g., (Int,Bool) and [[Char]]. elem :: Eq a => a -> [a] -> Bool elem x []= False elem x (y:ys)= (x == y) || elem x ys

© M. Winter COSC 4P41 – Functional Programming Classes (cont’d) (+1) :: Int -> Int elem (+1) [] causes an error No instance for (Eq (a0 -> a0)) arising from a use of `elem' Possible fix: add an instance declaration for (Eq (a0 -> a0)) In the expression: elem (+ 1) [] In an equation for `it': it = elem (+ 1) [] which conveys the fact that Int -> Int is not an instance of the Eq class.

© M. Winter COSC 4P41 – Functional Programming Instances of classes Examples: instance Eq Bool where True == True = True False == False = True _ == _ = False instance Eq a => Eq [a] where [] == [] = True (x:xs) == (y:ys) = x==y && xs==ys _ == _ = False instance (Eq a, Eq b) => Eq (a,b) where (x,y) == (z,w) = x==z && y==w

© M. Winter COSC 4P41 – Functional Programming Default definitions The Haskell Eq class is in fact defined by class Eq a where (==), (/=) :: a -> a -> Bool x /= y= not (x==y) x == y= not (x/=y) Both functions have default definitions in terms of the other function. At any instance a definition of at least one of == and /= needs to be provided.

© M. Winter COSC 4P41 – Functional Programming Derived classes To be ordered, a type must carry operations >, >= and so on, as well as the equality operations. class (Eq a) => Ord a where compare :: a -> a -> Ordering ( =), (>) :: a -> a -> Bool max, min :: a -> a -> a

© M. Winter COSC 4P41 – Functional Programming Example class Visible a where toString :: a -> String size:: a -> Int instance Visible Bool where toString True= ”True” toString False= ”False” size _= 1 instance Visible a => Visible [a] where toString= concat. map toString size= foldr (+) 1. map size

© M. Winter COSC 4P41 – Functional Programming Example (cont’d) sort :: Ord a => [a] -> [a] vSort :: (Ord a, Visible a) => [a] -> String vSort = toString. sort class (Ord a, Visible a) => OrdVis a vSort' :: OrdVis a => [a] -> String vSort' = toString. sort

© M. Winter COSC 4P41 – Functional Programming A tour of the built-in Haskell classes Many of the Haskell built-in classes are numeric, and are built to deal with overloading of the numerical operations. We will not study those classes. Class Eq: class Eq a where (==), (/=) :: a -> a -> Bool x /= y= not (x==y) x == y= not (x/=y) Instances: All except of IO, ->

© M. Winter COSC 4P41 – Functional Programming Class Ord class (Eq a) => Ord a where compare :: a -> a -> Ordering ( =), (>) :: a -> a -> Bool max, min :: a -> a -> a -- Minimal complete definition: (<=) or compare -- using compare can be more efficient for complex types compare x y | x==y = EQ | x<=y = LT | otherwise = GT x <= y = compare x y /= GT x < y = compare x y == LT x >= y = compare x y /= LT x > y = compare x y == GT max x y | x <= y = y | otherwise = x min x y | x <= y = x | otherwise = y Instances: All except IO, IOError, ->

© M. Winter COSC 4P41 – Functional Programming Class Enum class Enum a where succ, pred :: a -> a toEnum :: Int -> a fromEnum :: a -> Int enumFrom :: a -> [a] -- [n..] enumFromThen :: a -> a -> [a] -- [n,m..] enumFromTo :: a -> a -> [a] -- [n..m] enumFromThenTo :: a -> a -> a -> [a] -- [n,n'..m] -- Minimal complete definition: toEnum, fromEnum succ = toEnum. (1+). fromEnum pred = toEnum. subtract 1. fromEnum enumFrom x = map toEnum [ fromEnum x..] enumFromTo x y = map toEnum [ fromEnum x.. fromEnum y ] enumFromThen x y = map toEnum [ fromEnum x, fromEnum y..] enumFromThenTo x y z = map toEnum [ fromEnum x, fromEnum y.. fromEnum z ] Instances: (), Bool, Char, Int, Integer, Float Double

© M. Winter COSC 4P41 – Functional Programming Class Bounded class Bounded a where minBound, maxBound :: a -- Minimal complete definition: All Instances: Int, Char, Bool (but not Integer )

© M. Winter COSC 4P41 – Functional Programming Class Show type ShowS = String -> String class Show a where show :: a -> String showsPrec :: Int -> a -> ShowS showList :: [a] -> ShowS -- Minimal complete definition: show or showsPrec show x = showsPrec 0 x "" showsPrec _ x s = show x ++ s showList [] = showString "[]" showList (x:xs) = showChar '['. shows x. showl xs whereshowl [] = showChar ']' showl (x:xs) = showChar ','. shows x. showl xs Instances: All except ->

© M. Winter COSC 4P41 – Functional Programming Class Read type ReadS a = String -> [(a,String)] class Read a where readsPrec :: Int -> ReadS a readList :: ReadS [a] -- Minimal complete definition: readsPrec readList = readParen False (\r -> [pr | ("[",s) <- lex r, pr <- readl s ]) where readl s = [([],t) | ("]",t) <- lex s] ++ [(x:xs,u) | (x,t) <- reads s, (xs,u) <- readl' t] readl' s = [([],t) | ("]",t) <- lex s] ++ [(x:xs,v) | (",",t) <- lex s, (x,u) <- reads t, (xs,v) <- readl' u] Instances: All except IO, ->