User Tools

Site Tools


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 Prelude already consists of many type classes
    • Type classes in Prelude
      • type classes are in bold
      • below all types that have implemented instances
      • e.g. type class Num has implemented instances for the following types
        • Int
        • Integer
        • Float
        • Double
  • 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:
      ...
This website uses cookies. By using the website, you agree with storing cookies on your computer. Also you acknowledge that you have read and understand our Privacy Policy. If you do not agree leave the website.More information about cookies
You could leave a comment if you were logged in.
codesnippets/typeclasses.1618062585.txt.gz · Last modified: (external edit)

Except where otherwise noted, content on this wiki is licensed under the following license: CC0 1.0 Universal
CC0 1.0 Universal Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki