我正在研究一些Haskell(请原谅新手错误) -
这个例程出错了.我对do&< - 语法的理解是它们从monad中提取非Monad类型.所以理解是有缺陷的:这里的正确理解是什么?
exister :: String -> Bool
exister path = do
fileexist <- doesFileExist path
direxist <- doesDirectoryExist path
return fileexist || direxist
Run Code Online (Sandbox Code Playgroud)
错误
ghc -o joiner joiner.hs
joiner.hs:53:2:
Couldn't match expected type `Bool' against inferred type `m Bool'
In the first argument of `(||)', namely `return fileexist'
In the expression: return fileexist || direxist
In the expression:
do { fileexist <- doesFileExist path;
direxist <- doesDirectoryExist path;
return fileexist || direxist }
Run Code Online (Sandbox Code Playgroud)
Jos*_*Lee 11
第一个问题:该行return fileexist || direxist被解析为(return fileexist) || direxist,并且您不能m Bool作为第一个参数传递||.将其更改为return (fileexist || direxist).
第二个问题:你声称返回类型exister是Bool,但编译器推断它必须是IO Bool.修理它.(do和<-语法允许您a从m a值中提取值,但前提是您保证返回m a值.)
你给出的类型exister :: String -> Bool是一个返回普通非monadic的函数Bool.您正在执行的操作,doesFileExist path并且doesDirectoryExist path具有类型IO Bool,因此m Bool错误消息中的确实意味着IO Bool.如果更改exister要返回IO Bool的类型,则类型将是您想要的类型.
另外,在最后一行,你需要更多的parens : return (fileexist || direxist).