Reputation: 137
I'm trying to print a group of words and each words length in Haskell. The words are within a .txt file so first I have to get the contents into Haskell and then I split them into single words, so I did this so far:
main =
do
textdat <- openFile "palindrom.txt" ReadMode
inhalt <- hGetContents textdat
winhalt <- return (words inhalt)
print winhalt
putStrLn "has the length "
print (length winhalt)
palindrom.txt is the .txt file im taking the words from. with openFile and hGetContents, I assigned the content of the .txt to "inhalt". "winhalt" is the content split up into words with the "words"-fuction. Now im Getting this result:
"wordexample1""wordexample2""wordexample3"..."wordexample45"
has the length
45
(45 is the amount of words in the .txt file)
How can I split the sequence of words into single words so I can get and print the length of each word respectively?
Upvotes: 2
Views: 191
Reputation: 76366
If you run this code (on its own source code):
main = do
contents <- readFile "words.hs"
print $ [(w, length w) | w <- words contents]
You get
[("main",4),("=",1),("do",2),("contents",8),("<-",2),("readFile",8),("\"words.hs\"",10),("print",5),("$",1),("[(w,",4),("length",6),("w)",2),("|",1),("w",1),("<-",2),("words",5),("contents]",9)]
Of course, you can format the output:
main = do
contents <- readFile "words.hs"
putStr $ unlines [w ++ ": " ++ show (length w) | w <- words contents]
Upvotes: 1