我正在尝试将文件读入函数以计算文件中字符的频率。所以我正在尝试以下方法:
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.
答案 0 :(得分:1)
由于calculate
调用readFile
函数返回包含在IO
monad中的值,函数calculate
也必须返回IO
值,并且调用charCount
(纯计算)的结果必须return
才能将[(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)