I am trying to take a file name into my program and then read the file line by line into a list of string. I want the entire file to be read before going onto the rest of the program. My file I am trying to read is also about 10K lines. I also need to check each lines length to be able to put them into different lists. I currently have:
stageone :: String->[[String]]
stageone xs = do
fileLines <-readFile.xs
let line = lines fileLines
xss -- dont know where to go from here
A simple way to read the file strictly is to use Text
, which has a strict readFile
by default:
import qualified Data.Text as Text
import qualified Data.Text.IO as Text
main = do
ls <- fmap Text.lines (Text.readFile "filename.txt")
... -- The world is your oyster!
By the second line of the program the entire file will have been processed already.
It's a good habit to learn to use Text
instead of String
, since Text
is more efficient. To learn more about the text
library, you can begin here.
Welcome to Haskell. Unfortunately, your function's type signature won't work. You can't get away from the IO monad here.
stageone :: String -> IO [[String]]
is what you will end up with.
What you want to do is break up your requirements into functions and implement each one. These functions might be able to be pure functions without IO. Then come back and put them all together. This is how Haskell code is developed. Pay attention to the type signatures. If you get stumped, try to write just the signature and work from there.
How do you determine the length of a line?
How do you apply a function to each item in a list and keep the result?
How do you read a line from a file?
Once you have 10K line lengths, then what? Write them out? Print them?
Once you make the plan you can write and test these smaller pieces in ghci
.
Good luck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With