User Tools

Site Tools


codesnippets:typeclasses

Type classes and its instances, and the deriving mechanism

  • 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
  • additionally, there is many other libraries available with important type classes
  • example, implementing an Enum type class, and an instance for a data type
  • example, implementing a Show type class, and an instance for a data type
    • function show is implemented to covert every possible value of MyInt into a String
    • code:
      import Prelude hiding (Show(..))
       
      main :: IO ()
      main = putStrLn (show x1)
       
      class  Show a  where
          show :: a -> String
       
      data MyInt = C0 | C1 | C2 | C3
       
      instance Show MyInt where
          show C0 = "C0"
          show C1 = "C1"
          show C2 = "C2"
          show C3 = "C3"
       
      x1 = C3
    • executes, with output:
      C3
  • example, implementing an instance of the Prelude class Show for a data type
    • function show is implemented again for MyInt
    • code:
      main :: IO ()
      main = putStrLn (show x1)
       
      data MyInt = C0 | C1 | C2 | C3
       
      instance Show MyInt where
          show C0 = "C0"
          show C1 = "C1"
          show C2 = "C2"
          show C3 = "C3"
       
      x1 = C3
    • executes, again with output:
      C3

Deriving mechanism

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.

  • example, where a data type applies deriving mechanism
    • to implement all function of typeclass Show, and Enum
    • code:
      main :: IO ()
      main = putStrLn (show x1)
       
      data MyInt = C0 | C1 | C2 | C3
          deriving (Show, Enum)
       
      x1 = succ C1
    • executes, again with output:
      C2

Advanced type classes

  • example, implementing a Functor

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.txt · Last modified: by 127.0.0.1

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