为什么此IO处理不起作用(IO(非此即彼))



我正在尝试提取"a";并且错误";b";来自IO类型的表达式(a或b(。

我有这个函数,它返回一个基于文件路径的解析文件

readFile' :: FilePath -> IO (Either a b)

这就是我试图提取a和b值的方法:

rFile :: FilePath -> String
rFile f = do
l <- readFile' f
case l of 
Right n -> show n
Left m  -> show m

这是错误消息:

Couldn't match type `IO' with `[]'
Expected type: [Either a b]
Actual type: IO (Either a b)
* In a stmt of a 'do' block: l <- readFile' f

rFile不能返回String值,只能返回IO String值。(或者更准确地说,do构造的结果必须是IO String值,而不是String。(

rFile :: FilePath -> IO String
rFile f = do
l <- readFile' f
return $ case l of 
Right n -> show n
Left m  -> show m

您可以使用fmapeither来摆脱显式事例分析和do语法。

rFile f = fmap (either show show) (readFile' f)

(显而易见的后续问题是,我如何从IO String中获得String,我不会在这里重复。出于所有实际意图和目的,你都不会。(

最新更新