繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM