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 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
- example, implementing a
Functor:...
- executes, with output:
...
You could leave a comment if you were logged in.
codesnippets/typeclasses.1618062627.txt.gz · Last modified: (external edit)

