[Haskell-cafe] How to read a file and return a String?
Richard A. O'Keefe
ok at cs.otago.ac.nz
Thu Sep 5 06:48:15 CEST 2013
The original poster wants to
- read a file
- get the contents as a String
- break the string into lines
- do something with the lines
- and presumably print the result
Easy. Put the following lines in a file called 'rf.hs':
file_name = "rf.hs"
main =
readFile file_name >>= \string -> putStr (process (lines string))
process lines = maximum lines ++ "\n"
Then
m% ghc rf.hs
m% ./rf
=> process lines = maximum lines ++ "\n"
Explanation:
readFile file_name
is an IO action which when performed will read the named file
and deliver a string
cmd1 >>= \x -> cmd2
is an IO action which when performed will first perform cmd1,
then bind its result to x, and then perform cmd2.
>>= is the fundamental operation for chaining actions together.
lines
is a plain old String -> [String] function
process
is a plain old [String] -> String function, whatever you want
putStr x
is an IO action which when performed will write x
The run time environment causes main to be performed.
More information about the Haskell-Cafe
mailing list