【问题标题】:How to print a group of words with each words length in Haskell如何在Haskell中打印一组具有每个单词长度的单词
【发布时间】:2017-05-09 08:16:49
【问题描述】:

我正在尝试在 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 的内容分配给“inhalt”。 “winhalt”是使用“words”功能将内容分成单词。 现在我得到这个结果:

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

(45是.txt文件的字数)

如何将单词序列拆分为单个单词,以便分别获取和打印每个单词的长度?

【问题讨论】:

    标签: haskell input split


    【解决方案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]                                                              
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多