Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: readfile line by line and put into list

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
like image 967
tucker19 Avatar asked Mar 20 '14 23:03

tucker19


2 Answers

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.

like image 56
Gabriella Gonzalez Avatar answered Sep 22 '22 02:09

Gabriella Gonzalez


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.

like image 42
Sean Perry Avatar answered Sep 23 '22 02:09

Sean Perry