Abstract Data Types
Functional Programming and ReasoningDr Hans Georg Schaathun University of Surrey
Spring 2010 – Week 4
Dr Hans Georg Schaathun Abstract Data Types Spring 2010 – Week 4 1 / 32
This session
After this session, you should
be able to use ADT-s in software design
be able to implement simple ADT-s in haskell based on a specification
Dr Hans Georg Schaathun Abstract Data Types Spring 2010 – Week 4 3 / 32
Modules
Modularisation
Divide large problems into smaller ones
solve each subproblem separately
Functions is one way to split large programs But large programs, with many functions,
would still be hard to structure
Modules allow you to split programs into multiple files
Each file is one module
Modules
Naming modules
module Ant where
It is good practice to give your modules a name The filename should match the module name
theAntmodule resides inAnt.hs
Modules
Sample module
module Ant where import Insect
data Ants = Queen Int Float | Worker Float anteater x = x - 1
Dr Hans Georg Schaathun Abstract Data Types Spring 2010 – Week 4 7 / 32
Modules
Importing modules
import Insect
Whenever you need functions from a module
youimportit
Access to all functions in the module
Dr Hans Georg Schaathun Abstract Data Types Spring 2010 – Week 4 8 / 32
Modules
Import Controls
Limited imports
import Ant ( Ants(..) )
Excluding functions
import Ant hiding ( anteater ) import Prelude hiding ( words )
Fully qualified names
import qualified Ant Ant.anteater
Local name
import Insect as Ant
importingAnt, but calling itInsect
All of these techniques may be important to avoid name clashes
Modules
Program versus module
We have not yet written a program
only modules
The hugs command line allows us to test modules
we can evaluate any expression testing any function in the module
A program needs to know what to evaluate
that is an objectmain
Modules
The
Main
module
A program needs a top-level moduleMain
module Main where
Defining an expressionmain
this expression is evaluated when the program is run
Themainexpression must be an IO type
we will discuss how to do this later (Week 9?)
Such a program can be run as a script
runhugs main.hs
or compiled using the Glasgow Haskell Compiler
Dr Hans Georg Schaathun Abstract Data Types Spring 2010 – Week 4 11 / 32
Modules
Sample
Main
module
module Main where
data Shape = Circle Float | Rectangle Float Float area :: Shape -> Float
area (Circle r) = pi*r^2 area (Rectangle x y) = x*y s :: Shape
s = Circle 2.3
main = print (area s)
Dr Hans Georg Schaathun Abstract Data Types Spring 2010 – Week 4 12 / 32
Modules
Software design
Which modules?
Each module should have
a clear purpose clear scope documentation
Maincontains the main routine
only definitions particular to this programme separate modules for reusable functions
Often, one module for each data type
including functions on the data type
Thinkabout how you split the program into modules
Abstract Data Types
Encapsulation
A module often contains many definitions
only a few are docuemented
intended for use in importing modules
many auxiliary definitions and features for internal use
This causes problems
information overload for the programmer using the module name clashes with other modules
Abstract Data Types
Example
Inventory of a Store
A data type to hold a library catalogue
Possiblytype Library = [(Book,Int)]
using yourBooktype from the exercises storing the number of copies
Do you need to know how the type is implemented? No. You need to know the functions working on the type.
getStock :: Library -> Book -> Int initial :: Library(empty library)
addBook :: Library -> Book -> Library
All functionality available via the functions You do not need to know the implementation
data Library = Lib [ (Book,Int) ], or
data Library = Lib (Book -> Int)
Dr Hans Georg Schaathun Abstract Data Types Spring 2010 – Week 4 16 / 32
Abstract Data Types
Abstract Datatype
An abstract data type (ADT) is a type which can only be accessed or manipulated using a limited set of clearly defined functions.
New functions must be defined in terms of the ‘primitive’ functions No direct access to the data
many things will be impossible
This prevents abuse of the data type
and thus prevents many errors
Dr Hans Georg Schaathun Abstract Data Types Spring 2010 – Week 4 17 / 32
Abstract Data Types
Defining an ADT
module Library( Library, initial, getStock, addBook ) where
We list explicitely which names to export
The typeLibraryis exported
its constructors arenot
Exported functions (initial,getStock,addBook) gives
access to the type
This Haskell’s ADT mechanism
Abstract Data Types
Export Controls
Export Controls can be used in different ways ADT-s are special in that
the constructors are hidden
module Library( Library(..), initial, getStock, addBook ) where
(..)means that the constructors should be exported as well this isnotan ADT
Abstract Data Types
Classes and Instances
Defining an ADT, you will often want to overload standard functions
instance Show Library where
Such instances arealwaysexported
Inherent properties of the data type
cannot be hidden
Dr Hans Georg Schaathun Abstract Data Types Spring 2010 – Week 4 20 / 32
Abstract Data Types
Advantages of ADT-s
Interchangeable
different implementations of the same ADT can be interchanged ...
as long as the specification is the same
Delegate the implementation
if you agree on the interface (functions) you know it will work with other modules
Updates with backwards compatibility
add features while continuing to support old ones
Dr Hans Georg Schaathun Abstract Data Types Spring 2010 – Week 4 21 / 32
Specification
Specification
A specification is a careful description of a program or module
formal specification languages (such as Z) natural language
It defines exactly how the module is intended to work
exactly which functions are supported
Specification
Specification example
Library catalogueA type Library
storing records of books number of copies per book
Required functions
addBook :: Library -> Book -> Library
add a new book to the library
if the book exists already, increase number of copies
initial :: Library
return a Library with no books
getStock :: Library -> Book -> Int
Specification
Why use specification
Software projects are big
communication and collaboration essential
Agreeing on specifications
allow independent implementation
One person can implement the ADT Others can write modules using the ADT
It is important to be able to program strictly to specifications
otherwise the modules won’t fit together
Dr Hans Georg Schaathun Abstract Data Types Spring 2010 – Week 4 25 / 32
Data Structures
Data structures
ADT-s are common for defining Data Structures
e.g. lists, queues, stacks, heaps, etc.
Holding large quantities of data
Different functions for data processing and access
sorting searching last/first element
Dr Hans Georg Schaathun Abstract Data Types Spring 2010 – Week 4 27 / 32
Data Structures
Example: Queue
First in, first out
Insert elements at the end of the queue Retrieve elements from the head of the queue Usually no searching
ADT functions
emptyQ(create empty queue)
isEmptyQ(is the queue empty?)
addQ(add element)
remQ(remove/retrieve element)
Data Structures
Different ways to define data types
data NewType = Cons1 T11 T12 ... | Cons2 T21 T22 ... | ...
algebraic data type – as discussed the most flexible construct
newtype NewType = Cons1 T1
special case with only one constructor and one argument more efficient (internally) thandata
otherwise equivalent
type NewType = ...
alias for another data type often tupples
Data Structures
Queue Implementation
module Queue(Queue,emptyQ,isEmptyQ,addQ,remQ) where newtype Queue a = Qu [a] -- parameterised
emptyQ - Qu []
isEmptyQ (Qu []) = True isEmptyQ _ = False
addQ x (Qu xs) = Qu ( xs++[x] )
remQ Qu ([]) = error "Cannot remove from empty queue" remQ Qu (x:xs) = (x,xs)
Dr Hans Georg Schaathun Abstract Data Types Spring 2010 – Week 4 30 / 32
Closing
Summary
Module allows structuring your program
An ADT is a module with a carefully controlled interface The coursework will require an ADT
you are given a front-end module
have to implement the ADT strictly to specification the use of ADT-s ensure compatibility