Saturday, 30 April 2016

Haskell: Phantom type


A phantom type is a parametrised type whose parameters do not all appear on the right-hand side of its definition.

For example,
data Employee a = Employee EmpId FirstName LastName

In above statement, the type variable ‘a’ is not used in data contructor.

What is the advantage of phantom type?
Let us assume, you are maintaining database of companies ABC, XYZ. Due to some organizational changes, Compnay ABC want to change their employee ids, but not XYZ. Following sample application achieve the same using phantom types.

Sample.hs
type FirstName = String
type LastName = String
type EmpId = Integer

data ABC
data XYZ

type EmpABC = Employee ABC
type EmpXYZ = Employee XYZ


data Employee a = Employee EmpId FirstName LastName

updateEmployeeIdForABC :: EmpABC -> EmpId-> EmpABC
updateEmployeeIdForABC (Employee empId firstName lastName) empId1 =  Employee empId1 firstName lastName

getEmployeeABC :: EmpId -> FirstName -> LastName -> EmpABC
getEmployeeABC empId firstName lastName = Employee empId firstName lastName

getEmployeeXYZ:: EmpId -> FirstName -> LastName -> EmpXYZ
getEmployeeXYZ empId firstName lastName = Employee empId firstName lastName

Prelude> :load Sample.hs
[1 of 1] Compiling Main             ( Sample.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> let emp1 = getEmployeeABC 1 "Hari" "Krishna"
*Main> let emp2 = getEmployeeXYZ 123 "Anand" "Bandaru"
*Main> 
*Main> :t emp1
emp1 :: EmpABC
*Main> 
*Main> :t emp2
emp2 :: EmpXYZ
*Main> 
*Main> updateEmployeeIdForABC emp1 34
Employee 34 "Hari" "Krishna"
*Main> 
*Main> updateEmployeeIdForABC emp2 345

<interactive>:13:24:
    Couldn't match type XYZ with ABC
    Expected type: EmpABC
      Actual type: EmpXYZ
    In the first argument of updateEmployeeIdForABC, namely emp2
    In the expression: updateEmployeeIdForABC emp2 345


Previous                                                 Next                                                 Home

No comments:

Post a Comment