Haskell readFile:无法将预期类型'[String]'与实际类型'IO String'匹配

时间:2015-11-29 03:20:12

标签: string haskell io ghc ghci

我正在尝试将文件读入函数以计算文件中字符的频率。所以我正在尝试以下方法:

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.

1 个答案:

答案 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)