In this chapter I will use ideas developed in the last chapter to extend the functionality of geometric shapes defined in Chapter 2. In particular, we will consider the problem of combining shapes into larger, possibly overlapping, regions. We will not be interested in computing the area or perimeter of these regions (no easy task, by the way, with the shapes allowed to overlap in arbitrary ways), but rather we will want to know whether a particular point lies within a region. Regions are thus located on a two-dimensional (i.e., Cartesian) plane.
The functionality that we develop will be encapsulated in a module called Region:
module Region (Region (Shape, Translate, Scale, Complement, Union, Intersect, Empty),
Coordinate,
containsS, containsR,
module Shape
)where
import Shape
Note that this module imports the Shape module, and exports a data type called Region, functions containsS and containsR, and the entire Shape module.
The Region Data Type
Our first task will be to define a data type that captures the various kinds of regions that interest us:
– – A Region is either:
data Region = Shape Shape – – primitive shape
| Translate Vector Region – – translated region
| Scale Vector Region — scaled region
| Complement Region – – inverse of region
| Region ‘Union’ Region – – union of regions
| Region ‘Intersect’ Region – –intersection of regions
| Empty – – empty region
deriving Show
type Vector = (Float, Float)
DETAILS
The first line here looks odd: The name Shape appears twice in Shape Shape, The first occurrence, however, is the name of a new constructor in the Region data type, whereas the second is the name of an existing data type defined In Chapter 2, Haskell allows using the same name to define a constructor and a data type because they can never be confused. The context in which they are used will always be sufficient to distinguish them.
This example also demonstrates the use of program comments. Any text to the right of “––” until the end of the line is considered to be a comment and is effectively ignored by a Haskell implementation, Haskell also permits nested comments, which have the form {- this is a comment -} and can appear anywhere in a program.
Review the options below to login to check your access.
Log in with your Cambridge Aspire website account to check access.
If you believe you should have access to this content, please contact your institutional librarian or consult our FAQ page for further information about accessing our content.