-->

Haskell file reading

2019-01-21 22:35发布

问题:

I have just recently started learning Haskell and I am having a lot of trouble trying to figure out how the file reading works.

For example, I have a text file "test.txt" And it contains lines of numbers eg:

32 4
2 30
300 5

I want to read each line and then evaluate each word and add them. Thus I am trying to do something like this so far:

import System.IO  
import Control.Monad

main = do  
        let list = []
        handle <- openFile "test.txt" ReadMode
        contents <- hGetContents handle
        singlewords <- (words contents)
        list <- f singlewords
        print list
        hClose handle   

f :: [String] -> [Int]
f = map read

I know this is completely wrong, but I don't know how to use the syntax correctly at all. Any help will be greatly appreciated. As well as links to good tutorials that have examples and explanation of code except this one: http://learnyouahaskell.com/input-and-output I have read it fully

回答1:

Not a bad start! The only thing to remember is that pure function application should use let instead of the binding <-.

import System.IO  
import Control.Monad

main = do  
        let list = []
        handle <- openFile "test.txt" ReadMode
        contents <- hGetContents handle
        let singlewords = words contents
            list = f singlewords
        print list
        hClose handle   

f :: [String] -> [Int]
f = map read

This is the minimal change needed to get the thing to compile and run. Stylistically, I have a few comments:

  1. Binding list twice looks a bit shady. Note that this isn't mutating the value list -- it's instead shadowing the old definition.
  2. Inline pure functions a lot more!
  3. When possible, using readFile is preferable to manually opening, reading, and closing a file.

Implementing these changes gives something like this:

main = do  
        contents <- readFile "test.txt"
        print . map readInt . words $ contents
-- alternately, main = print . map readInt . words =<< readFile "test.txt"

readInt :: String -> Int
readInt = read


回答2:

Daniel Wagner's solution is a great one. Here is another swing at it so you can get some more ideas about efficient file handling.

{-#  LANGUAGE OverloadedStrings #-}
import System.IO
import qualified Data.ByteString.Lazy.Char8 as B
import Control.Applicative
import Data.List

sumNums :: B.ByteString -> Int
sumNums s = foldl' sumStrs 0 $ B.split ' ' s

sumStrs :: Int -> B.ByteString -> Int
sumStrs m i = m+int
              where Just(int,_) = B.readInt i

main = do 
  sums <- map sumNums <$> B.lines <$> B.readFile "testy"
  print sums

First, you'll see the OverloadedStrings pragma. This allows use to just use normal quotes for string literals that are actually bytestrings. We will be using Lazy ByteStrings for processing the file for several reasons. First, it allows us to stream the file through the program rather than forcing it all into memory at once. Also, bytestrings are faster and more efficient than strings in general.

Everything else is pretty much straightforward. We readFile the file into a lazy list of lines, and then map a summing function over each of the lines. The <$> are just shortcuts to allow us to operate on the value inside of IO() functor -- if this is too much I apologize. I just mean that when you readFile you don't get back a ByteString, you get back a ByteString wrapped in IO an IO(ByteString). The <$> says "Hey' I want to operate on the thing inside the IO and then wrap it back up.

B.split separates each line into numbers based on whitespace. (We could also use B.words for this) The only other interesting part is the in sumStrs we use deconstruction/pattern matching to extract the first value out of the Just that is returned by the readInt function.

I hope this was helpful. Ask if you have any questions.



回答3:

For all you non-functional programmers out there here is a treat

unsafePerformIO . readFile $ "file.txt"

Reads a file into a string

No IO String, just a normal fully loaded string ready for use. This might not be the right way but it works and no need to change your existing functions to suit IO String

p.s. Dont forget to import

import System.IO.Unsafe