P. 1
haskell2010

haskell2010

|Views: 71|Likes:
Published by nricci02

More info:

Categories:Types, Research, Science
Published by: nricci02 on Apr 14, 2011
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

04/28/2013

pdf

text

original

As a complete example, consider a tree datatype:

data Tree a = Leaf a | Tree a :ˆ: Tree a
deriving (Eq, Ord, Read, Show)

Automatic derivation of instance declarations for Bounded and Enum are not possible, as Tree is not
an enumeration or single-constructor datatype. The complete instance declarations for Tree are shown in
Figure 11.1, Note the implicit use of default class method definitions—for example, only <= is defined for
Ord, with the other class methods (<, >, >=, max, and min) being defined by the defaults given in the class
declaration shown in Figure 6.1.

150

CHAPTER 11. SPECIFICATION OF DERIVED INSTANCES

infixr 5 :ˆ:
data Tree a = Leaf a | Tree a :ˆ: Tree a

instance (Eq a) => Eq (Tree a) where
Leaf m == Leaf n = m==n
u:ˆ:v == x:ˆ:y = u==x && v==y
_ == _

= False

instance (Ord a) => Ord (Tree a) where
Leaf m <= Leaf n = m<=n
Leaf m <= x:ˆ:y = True
u:ˆ:v <= Leaf n = False
u:ˆ:v <= x:ˆ:y = u

instance (Show a) => Show (Tree a) where

showsPrec d (Leaf m) = showParen (d > app_prec) showStr

where

showStr = showString "Leaf " . showsPrec (app_prec+1) m

showsPrec d (u :ˆ: v) = showParen (d > up_prec) showStr

where

showStr = showsPrec (up_prec+1) u .
showString " :ˆ: "

.

showsPrec (up_prec+1) v
-- Note: right-associativity of :ˆ: ignored

instance (Read a) => Read (Tree a) where

readsPrec d r = readParen (d > up_prec)
(\r -> [(u:ˆ:v,w) |

(u,s) <- readsPrec (up_prec+1) r,
(":ˆ:",t) <- lex s,
(v,w) <- readsPrec (up_prec+1) t]) r

++ readParen (d > app_prec)
(\r -> [(Leaf m,t) |

("Leaf",s) <- lex r,
(m,t) <- readsPrec (app_prec+1) s]) r

up_prec = 5 -- Precedence of :ˆ:
app_prec = 10 -- Application has precedence one more than
-- the most tightly-binding operator

Figure 11.1: Example of Derived Instances

Chapter 12

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->