2017-05-09 51 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]                
相關問題