![](/img/trans.png)
[英]Haskell Couldn't match expected type 'String' with actual type 'Char'
[英]Haskell readFile: Couldn't match expected type ‘[String]’ with actual type ‘IO String’
我正在尝试将文件读入一个函数来计算文件中字符的频率。 所以我正在尝试以下操作:
charCount :: String -> [(Char, Int)]
charCount input = M.toList $ M.fromListWith (+) [(c, 1) | c <- input]
calculate :: FilePath -> [(Char, Int)]
calculate fp = do
c <- readFile fp
charCount c
但我收到以下错误:
FileWriter.hs:13:8: Couldn't match expected type ‘[String]’ …
with actual type ‘IO String’
In a stmt of a 'do' block: c <- readFile fp
In the expression:
do { c <- readFile fp;
charCount c }
Compilation failed.
由于calculate
调用readFile
返回包装在一个价值函数IO
单子函数calculate
必须返回一个IO
值也和调用的结果charCount
(纯计算)必须return
ED以包住[(Char, Int)]
变成一个 monad。
下一个示例适用于ghc 7.10.1
:
import qualified Data.Map as M
charCount :: String -> [(Char, Int)]
charCount input = M.toList $ M.fromListWith (+) [(c, 1) | c <- input]
calculate :: FilePath -> IO [(Char, Int)]
calculate fp =
readFile fp >>= \c ->
return (charCount c)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.