Saturday 30 April 2016

Haskell: type: make type synonyms


In previous post, I explained how to define custom types using data keyword. In this post,  am going to explain how to make clear code using both data and type keywords. 'type' keyword is used to define synonyms for an existing type.

type firstName = String

Above code says that firstName is a synonym for a String. Any function that takes a String will now take a Name as well and vice-versa. Type synonyms are mainly used to make the code more readable.

customType.hs
{- Synonyms for existing types-}
type Id = Int
type FirstName = String
type LastName = String

type Year = Int
type Month = Int
type Day = Int

type Salary = Double

type BirthDate = Date

{- Custom Types -}
data Date = Date Year Month Day

data Employee = Engineer Id FirstName LastName BirthDate
                | Manager Id FirstName LastName Salary BirthDate

showBasicInfo id firstName lastName = "id = " ++ (show id) ++ " firstName = " ++ firstName ++ " lastName = " ++ lastName

showBirthDate (Date year month day) = "Year : " ++ (show year) ++ " Month : " ++ (show month ) ++ " Day : " ++ (show day)

getEmployee (Engineer id firstName lastName date) = showBasicInfo id firstName lastName ++ " Birth Date : " ++ showBirthDate date

getEmployee (Manager id firstName lastName salary date) = showBasicInfo id firstName lastName ++ " salary = " ++ (show salary) ++ " Birth Date : " ++ showBirthDate date

*Main> :l customType.hs
[1 of 1] Compiling Main             ( customType.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> 
*Main> let ptrBirthday = Date 1988 6 6
*Main> 
*Main> let ptr = Engineer 1 "Sailu" "PTR" ptrBirthday
*Main> 
*Main> getEmployee (ptr)
"id = 1 firstName = Sailu lastName = PTR Birth Date : Year : 1988 Month : 6 Day : 6"


Previous                                                 Next                                                 Home

No comments:

Post a Comment