Sunday 22 May 2016

Haskell: readFile : Get file data as a string


Haskell, System.IO module provides readFile function, which reads file data as string. The file is read lazily, on demand.

FileUtils.hs
import System.IO

main = do
        fileName <- getLine
        information <- readFile fileName
        putStrLn information

$ ghc FileUtil.hs
[1 of 1] Compiling Main             ( FileUtil.hs, FileUtil.o )
Linking FileUtil ...
$ ./FileUtil
/Users/harikrishna_gurram/quotes.txt

"If you love a flower, don’t pick it up. Because if you pick it up it dies and it ceases to be what you love. So if you love a flower, let it be. Love is not about possession. Love is about appreciation."

"Experience life in all possible ways -- good-bad, bitter-sweet, dark-light, summer-winter. Experience all the dualities. Don't be afraid of experience, because the more experience you have, the more mature you become."

  Lets talk some thing in imperative language sense. Suppose you had a big file of size 10GB, your RAM capacity is of size 2 GB. Your task is  to convert every character in the file to uppercase. If you written a function like ‘readFile fileName’, since imperative languages are not lazy, readFile  function supposed to read entire file to RAM and convert it to string, which is not possible since RAM size is 2GB.

In case of lazy languages like Haskell, you no need to worry about above situations, it read the contents of file whenever it is required and all functions also work in lazy manner, they work with whatever the data available to them.

FileUtil.hs
import System.IO
import Data.Char

main = do
        putStrLn "Enter filename (Including full path)"
        fileName <- getLine
        information <- readFile fileName
        putStrLn (map toUpper information)

$ ghc FileUtil.hs
[1 of 1] Compiling Main             ( FileUtil.hs, FileUtil.o )
Linking FileUtil ...
$ ./FileUtil
Enter filename (Including full path)
/Users/harikrishna_gurram/quotes.txt

"IF YOU LOVE A FLOWER, DON’T PICK IT UP. BECAUSE IF YOU PICK IT UP IT DIES AND IT CEASES TO BE WHAT YOU LOVE. SO IF YOU LOVE A FLOWER, LET IT BE. LOVE IS NOT ABOUT POSSESSION. LOVE IS ABOUT APPRECIATION."

"EXPERIENCE LIFE IN ALL POSSIBLE WAYS -- GOOD-BAD, BITTER-SWEET, DARK-LIGHT, SUMMER-WINTER. EXPERIENCE ALL THE DUALITIES. DON'T BE AFRAID OF EXPERIENCE, BECAUSE
THE MORE EXPERIENCE YOU HAVE, THE MORE MATURE YOU BECOME."


Previous                                                 Next                                                 Home

No comments:

Post a Comment