2017-05-09 94 views
2

我试图在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文件IM采取的话。通过openFile和hGetContents,我将.txt的内容分配给“inhalt”。 “winhalt”是将内容与“文字” - 功能分成单词。 现在即时得到这样的结果:

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

(45字的数量,在txt文件)

我怎么能分开单词为单个单词的顺序,以便我能获得和打印长度每个词的分别?

回答

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]                
相关问题