Haskell file reading
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:
- Binding
list
twice looks a bit shady. Note that this isn't mutating the valuelist
-- it's instead shadowing the old definition. - Inline pure functions a lot more!
- 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
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.