>我有一个函数来计算每个单词在字符串中重复的次数:
keywords :: String -> [String]
keywords = words . map (x -> if isAlpha x then x else ' ')
count :: Ord a => [a] -> [(a,Int)]
count = map (head &&& length) . group . sort
wordcount = count . keywords
这很完美。
我想使用 IO 读取文本文件作为此函数的输入。我像这样编码:
wordcou :: IO ()
wordcou =
do
putStr "Please text file name :"
textfile <- getLine
text <- readFile textfile
let result = wordcount text
putStr result
IO 函数给我一个错误。任何人都可以帮我解决此错误吗?
错误是
ERROR file:.project.hs:194 - Type error in application
*** Expression : putStr result
*** Term : result
*** Type : [([Char],Int)]
*** Does not match : [Char]
您的代码有 2 个问题:
-
wordcou
应该是IO ()
类型,因为它不返回任何内容 -
putStr
应该用print
代替,因为结果不是String
进行这些更改后,代码将编译并正常运行。
为 wordcount
添加类型声明。
看看putStr
和print
的类型和定义。你看出区别了吗?