codesnippets:typeclasses
This is an old revision of the document!
Type classes and its instances
- A type class (keyword:
class) is a set of functions declarations that- can have generic default bindings, and
- have instances (keyword:
instance) with type specific bindings.
- module
Preludealready consists of many type classes-
- type
classes are in bold - below all types that have implemented instances
- e.g. type
classNumhas implementedinstances for the following typesIntIntegerFloatDouble
-
- example, implementing an
Enumtype class, and an instance for a data type- functions
succ, andpredhave default implementations inclass Enum,- which have been overridden in the
instance Enum MyIntof
- code:
import Prelude hiding (Enum(..)) main :: IO () main = do print 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)))
- executes, with output:
2
- example, implementing a
Functor:import Prelude hiding (Maybe(..), Functor(..)) main :: IO () main = do print x1 class Functor f where fmap :: (a -> b) -> f a -> f b data Maybe a = Just a | Nothing deriving Show instance Functor Maybe where fmap f (Just x) = Just (f x) fmap _ Nothing = Nothing x1 = fmap (+3) (Just 2)
- executes, with output:
Just 5
You could leave a comment if you were logged in.
codesnippets/typeclasses.1618066325.txt.gz · Last modified: (external edit)

