Sunday, 1 May 2016

Haskell: Defining type class instances


In my previous post, I explained how to define type classes. In this post I am going to explain how to define instances of type classes.

Syntax
instance TypeClass Type where
    function1 == implementation
    function2 == implementation
       ....
       ....
    functionN == implementation

Following example shows you how to create instance for type class Equal and implement the functions declared in the type class Equal.

CustomTypes.hs
module CustomTypes where
    type FirstName = String
    type LastName = String
    type EmpId = Integer
    type NoOfReportees = Integer

    {- Define an employee type -}
    data Employee = Engineer FirstName LastName EmpId
                   | Manager FirstName LastName EmpId NoOfReportees
                   | Director FirstName LastName EmpId NoOfReportees


CustomTypeClasses.hs
import CustomTypes

class Equal a where

    isEquals :: a -> a -> Bool

    isNotEquals :: a -> a -> Bool
    isNotEquals x y = not (isEquals x y)

instance Equal Employee where
    isEquals (Engineer firstName1 lastName1 empId1) (Engineer firstName2 lastName2 empId2) =
        (firstName1 == firstName2) && (lastName1 == lastName2) && (empId1 == empId2)

    isEquals (Manager firstName1 lastName1 empId1 noOfReportees1) (Manager firstName2 lastName2 empId2 noOfReportees2) =
        (firstName1 == firstName2) && (lastName1 == lastName2) && (empId1 == empId2)

    isEquals (Director firstName1 lastName1 empId1 noOfReportees1) (Director firstName2 lastName2 empId2 noOfReportees2) =
        (firstName1 == firstName2) && (lastName1 == lastName2) && (empId1 == empId2)


Type class Equal declared two functions isEquals, isNotEquals. It provides default implementation for isNotEquals function. If we don’t explicitly define isNotEquals, the compiler automatically uses the default implementation given in the type class Equal.

isEquals :: a -> a -> Bool
isNotEquals :: a -> a -> Bool
*Main> :load CustomTypeClasses.hs 
[1 of 2] Compiling CustomTypes      ( CustomTypes.hs, interpreted )
[2 of 2] Compiling Main             ( CustomTypeClasses.hs, interpreted )
Ok, modules loaded: Main, CustomTypes.
*Main> 
*Main> let engineer1 = Engineer "Hari Krishna" "Gurram" 1
*Main> let engineer2 = Engineer "Hari" "Gurram" 1
*Main> 
*Main> isEquals engineer1 engineer2
False
*Main> 
*Main> isNotEquals engineer1 engineer2
True
*Main> 




Previous                                                 Next                                                 Home

No comments:

Post a Comment