Saturday, 30 April 2016

Haskell: generate String representation of custom type


By using 'deriving Show' type class at the time of defining custom type, you can automatically generate default string representation for custom types. Show is a type class, by deriving it, you can get the string representation of type.

Example
data Employee = Engineer Int String String | Manager Int String String Double deriving Show
Prelude> data Employee = Engineer Int String String | Manager Int String String Double deriving Show 
Prelude> 
Prelude> let engineer1 = Engineer 1 "Hari Krishna" "Gurram"
Prelude> 
Prelude> let manager1 = Manager 1 "Vadi Raj" "Kulkarni" 12345678.23
Prelude> 
Prelude> show engineer1
"Engineer 1 \"Hari Krishna\" \"Gurram\""
Prelude> 
Prelude> show manager1
"Manager 1 \"Vadi Raj\" \"Kulkarni\" 1.234567823e7"
Prelude> 

Previous                                                 Next                                                 Home

No comments:

Post a Comment