[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"
readFile file_name >>= \string -> putStr (process (lines string))
process lines = maximum lines ++ "\n"
m% ghc rf.hs
=> process lines = maximum lines ++ "\n"
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.
is a plain old String -> [String] function
is a plain old [String] -> String function, whatever you want
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