[More work on ch5 John Goerzen **20070610202432] { hunk ./en/ch05-typeclasses.xml 204 - FIXME + Now that you know how to define typeclasses, it's time to learn how to + define instances of typeclasses. An instance is just a type. Making + it an instance of a particular typeclass means implementing the + functions necessary for that typeclass. + + + Recall our attempt to create a test for equality over a + Color type back in . FIXME: + how can we insert the page number here? --jg + Now let's see how we could make that same Color + type a member of the BasicEq3 class. + + &eqclasses.hs:basiceq3inst; + + Notice that we provide essentially the same function as we used + back in . In fact, the + implementation is identical. However, in this case, we can use + isEqual3 on any type that + we declare is an instance of BasicEq3, not just + this one color type. We could define equality tests for any anything + from numbers to graphics using the same basic pattern. In fact, as you + will see in , this + works the same as making Haskell's == operator + work for your own custom types. + + + Note also that the BasicEq3 class defined both + isEqual3 and isNotEqual3, but we + defined only one of them. That's because of the default implementation + contained in BasicEq3. Since we didn't explicitly + define isNotEqual3, the compiler automatically uses + the default implementation given in the BasicEq3 + declaration. hunk ./en/ch05-typeclasses.xml 239 + hunk ./en/ch05-typeclasses.xml 270 + + + Automatic Derivation + + FIXME + + hunk ./examples/ch05/eqclasses.hs 44 +{-- snippet basiceq3inst --} +instance BasicEq3 Color where + isEqual3 Red Red = True + isEqual3 Red _ = False + isEqual3 Green Green = True + isEqual3 Green _ = False + isEqual3 Blue Blue = True + isEqual3 Blue _ = False +{-- /snippet basiceq3inst --} + + }