Sunday 1 May 2016

Haskell: Read: Convert string to some other data type


Read type class is just opposite to Show type class, it provides a function read, which takes a string and converts it to specific type.
Prelude> :t read
read :: Read a => String -> a


Observe above snippet, it is stating that read function take a String and convert it to value of type ‘a’ (‘a’ is an instance of type class Read).

Syntax
read "string" :: TypeToConvert
 
Prelude> read "10.02" :: Double
10.02
Prelude> read "10.02" :: Float
10.02
Prelude> read "10" :: Integer
10
Prelude> read "True" :: Bool
True


Following program calculates simple interest.
Let Principal = P, Rate = R% per annum (p.a.) and Time = T years. Then
 Simple Intereest = (P x R x T) /100

Interestutil.hs
simpleInterest = do
                   putStrLn ("Enter Principal")
                   inpStr <- getLine
                   let principal = (read inpStr) :: Double

                   putStrLn ("Enter time in months")
                   inpStr <- getLine
                   let time = (read inpStr) :: Integer

                   putStrLn ("Enter Rate Of Interest")
                   inpStr <- getLine
                   let rateOfInterest = (read inpStr) :: Double

                   let result = (principal * fromIntegral time * rateOfInterest) / 100

                   putStrLn ("Simple Interest : " ++ show (result))

*Main> :load InterestUtil.hs 
[1 of 1] Compiling Main             ( InterestUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> simpleInterest
Enter Principal
815
Enter time in months
36
Enter Rate Of Interest
2
Simple Interest : 586.8
*Main> 
*Main> simpleInterest
Enter Principal
100000
Enter time in months
12
Enter Rate Of Interest
1.10
Simple Interest : 13200.0
*Main> 


Applying both read and show on custom types
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)

*CustomTypes> :load CustomTypes.hs
[1 of 1] Compiling CustomTypes      ( CustomTypes.hs, interpreted )
Ok, modules loaded: CustomTypes.
*CustomTypes> 
*CustomTypes> let engineer1 = Engineer "Hari Krishna" "Gurram" 123
*CustomTypes> show engineer1
"Engineer \"Hari Krishna\" \"Gurram\" 123"
*CustomTypes> 
*CustomTypes> let str = show engineer1
*CustomTypes> let engg1 = read (show engineer1) :: Employee
*CustomTypes> engg1
Engineer "Hari Krishna" "Gurram" 123
*CustomTypes>





Previous                                                 Next                                                 Home

No comments:

Post a Comment