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
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.
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.
Not a bad start! The only thing to remember is that pure function application should use
let
instead of the binding<-
.This is the minimal change needed to get the thing to compile and run. Stylistically, I have a few comments:
list
twice looks a bit shady. Note that this isn't mutating the valuelist
-- it's instead shadowing the old definition.readFile
is preferable to manually opening, reading, and closing a file.Implementing these changes gives something like this:
For all you non-functional programmers out there here is a treat
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