如何在Haskell中打印每个单词长度的单词组

时间:2017-05-09 08:16:50

标签: haskell input split

我试图在Haskell中打印一组单词和每个单词的长度。单词在.txt文件中,所以首先我必须将内容放入Haskell然后我将它们分成单个单词,所以到目前为止我这样做了:

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是我从中获取单词的.txt文件。使用openFile和hGetContents,我将.txt的内容分配给&#34; inhalt&#34;。 &#34; winhalt&#34;是将内容分成单词&#34;单词&#34; -fuction。 现在我得到这个结果:

"wordexample1""wordexample2""wordexample3"..."wordexample45"
has the length
45

(45是.txt文件中的单词数量)

如何将单词序列分成单个单词,这样我才能分别得到并打印每个单词的长度?

1 个答案:

答案 0 :(得分:1)

如果您运行此代码(在其自己的源代码上):

main = do                                                                                                                                                                                               
    contents <- readFile "words.hs"
    print $ [(w, length w) | w <- words contents]

你得到了

[("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)]

当然,您可以格式化输出:

main = do  
    contents <- readFile "words.hs"
    putStr $ unlines [w ++ ": " ++ show (length w) | w <- words contents]                                                              
相关问题