P. 1
Haskel Tutorial

Haskel Tutorial

|Views: 132|Likes:
Publicado pordevilvsevil

More info:

Published by: devilvsevil on Oct 23, 2008
Direitos Autorais: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

09/07/2012

pdf

text

original

TheEqclass has two members (i.e., two functions):

(==) :: Eq a => a -> a -> Bool
(/=) :: Eq a => a -> a -> Bool

Thefirstofthesetypesignaturesreadsthatthefunction==isafunctionwhichtakes
two as which are members ofEqand produces aBool. The type signature of/=(not
equal) is identical. A minimal complete definition for the Eq class requires that either
one of these functions be defined (if you define==, then/=is defined automatically by
negating the result of ==, and vice versa). These declarations must be provided inside
the instance declaration.
This is best demonstrated by example. Suppose we have our color example, re-
peded here for convenience:

data Color
= Red
| Orange
| Yellow
| Green
| Blue
| Purple
| White
| Black
| Custom Int Int Int -- R G B components

We can define Color to be an instance ofEqby the following declaration:

instance Eq Color where
Red == Red = True
Orange == Orange = True
Yellow == Yellow = True
Green == Green = True
Blue == Blue = True
Purple == Purple = True
White == White = True

86

CHAPTER 7. ADVANCED FEATURES

Black == Black = True
(Custom r g b) == (Custom r’ g’ b’) =
r == r’ && g == g’ && b == b’
_ == _ = False

The first line here begins with the keyword instance telling the compiler that we’re
making an instance declaration. It then specifies the class, Eq, and the type, Color
which is going to be an instance of this class. Following that, there’s the where key-
word. Finally there’s the method declaration.
The first eight lines of the method declaration are basically identical. The first one,
for instance, says that the value of the expression Red == Red is equal to True.
Lines two through eight are identical. The declaration for custom colors is a bit differ-
ent. We pattern match Custom on both sides of ==. On the left hand side, we bind r,
g and b to the components, respectively. On the right hand side, we bind r’, g’ and
b’ to the components. We then say that these two custom colors are equal precisely
whenr == r’,g == g’andb == b’are all equal. The fallthrough says that any
pair we haven’t previously declared as equal are unequal.

You're Reading a Free Preview

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