Reputation: 41
I'm trying to read in a text file using Haskell, but based on my limited and little knowledge of the language, I'm have a bit of trouble an would like some help.
I have a text file with 1000+ random words, and would like to read in the text file I know that I have to
import System.IO
and maybe
import Data.List
and I have something like this:
main = do
let list = []
handle <- openFile "words.txt" ReadMode
contents <- hGetContents handle
but I don't know much more to proceed. Any help would be great. I've been stuck for a while now and have a deadline coming soon. Thank you!
Upvotes: 2
Views: 3053
Reputation: 78529
As was mentioned in the comments, the simplest way to do this is to use the readFile
function. readFile
is actually part of prelude (the base library), so you don't have to import anything.
contents <- readFile "words.txt"
will lazily load the entire file into the string contents
. Then, you can do various string processing to parse the file as you want. The function lines
(included by default as well) will split the contents
into a list of strings, splitting it on line breaks. The function words
will split contents
into a list of strings, splitting it on whitespace.
For more advanced methods, you can look into the System.IO library documention on Hackage. The documentation provided on Hackage tends to be clear and a really useful resource.
Keep up with Haskell! It's worth it.
Upvotes: 3