Sunday 1 May 2016

Haskell: Serialization using read and show


In my previous posts, I explained about read and show functions. ‘show’ function takes any type of data and convert it to string format, where as read function is opposite to show, which takes a string and converts it to specific type of data. By using show and read functions we can serialize our data. Serialization is a process of saving your data structure on disk and deserialization is a process of reading the data from disk and convert it to given data structure.

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
                   deriving (Show, Read)


I am going to serialize List of Employees to the file ser.out.

Serialize data
Prelude> :load CustomTypes.hs
[1 of 1] Compiling CustomTypes      ( CustomTypes.hs, interpreted )
Ok, modules loaded: CustomTypes.
*CustomTypes> 
*CustomTypes> let engineer1 = Engineer "Hari" "Krishna" 123
*CustomTypes> let engineer2 = Engineer "Sailaja" "PTR" 514
*CustomTypes> let manager1 = Manager "Anand" "Bandaru" 1234 35
*CustomTypes> let director1 = Director "Suhas" "Kulkarni" 234 59
*CustomTypes> 
*CustomTypes> let employees = [engineer1, engineer2, manager1, director1]
*CustomTypes> employees
[Engineer "Hari" "Krishna" 123,Engineer "Sailaja" "PTR" 514,Manager "Anand" "Bandaru" 1234 35,Director "Suhas" "Kulkarni" 234 59]
*CustomTypes> 
*CustomTypes> :t employees
employees :: [Employee]
*CustomTypes> 
*CustomTypes> let serializedData = show employees
*CustomTypes> 
*CustomTypes> writeFile "ser.out" serializedData
*CustomTypes> 


Let me explain what I did here.

I defined 4 variables (2 Engineers, 1 Manager, 1 Director).

let engineer1 = Engineer "Hari" "Krishna" 123
let engineer2 = Engineer "Sailaja" "PTR" 514
let manager1 = Manager "Anand" "Bandaru" 1234 35
let director1 = Director "Suhas" "Kulkarni" 234 59

Added above employees to a list.

let employees = [engineer1, engineer2, manager1, director1]

Get the string form of list of employees.
let serializedData = show employees

Write serializedData to ser.out file.

writeFile "ser.out" serializedData

You can see the contents of ser.out file using cat command in linux.
$ cat ser.out
[Engineer "Hari" "Krishna" 123,Engineer "Sailaja" "PTR" 514,Manager "Anand" "Bandaru" 1234 35,Director "Suhas" "Kulkarni" 234 59]localhost:programs harikrishna_gurram



 

Previous                                                 Next                                                 Home

No comments:

Post a Comment