class) is a set of functions declarations that instance) with type specific bindings.Prelude already consists of many type classesclasses are in boldclass Num has implemented instances for the following typesIntInteger FloatDoubleEnum type class, and an instance for a data typesucc, and pred have default implementations in class Enum, instance Enum MyInt of import Prelude hiding (Enum(..)) main :: IO () main = putStrLn (show x1) class Enum a where succ, pred :: a -> a succ = toEnum . (+ 1) . fromEnum pred = toEnum . (subtract 1) . fromEnum toEnum :: Int -> a fromEnum :: a -> Int data MyInt = C0 | C1 | C2 | C3 instance Enum MyInt where toEnum 0 = C0 toEnum 1 = C1 toEnum 2 = C2 toEnum 3 = C3 fromEnum C0 = 0 fromEnum C1 = 1 fromEnum C2 = 2 fromEnum C3 = 3 succ C3 = C0 succ x = (toEnum . (+ 1) . fromEnum) x pred C0 = C3 pred x = (toEnum . (subtract 1) . fromEnum) x x1 = fromEnum (succ (succ (succ C3)))
2
Show type class, and an instance for a data typeshow is implemented to covert every possible value of MyInt into a StringC3
instance of the Prelude class Show for a data typeshow is implemented again for MyIntC3
Looking to the examples above you may wonder, whether there an easier way to implement an instance of standard type classes. Yes, there is the deriving mechanism.
deriving mechanismShow, and EnumC2
FunctorJust 5