无法匹配预期类型
我想做一些不同的事情,但它太长了,所以下面只是示例:
test x y = if x == "5" then x
else do putStrLn "bad value"; y
所以如果 x == 5 它应该返回 x,否则它应该打印“坏值”并返回 y - 我如何在 haskell 中做到这一点?
编辑:
为什么此代码返回错误:“无法将预期类型 bool 与实际类型 IO bool 匹配”?
canTest :: String -> IO Bool
canTest x = if x == "5" then return True
else do putStrLn "bad value"; return False
test x y = if canTest x then x
else y
I would like to do something different but it would be too long so below is only example:
test x y = if x == "5" then x
else do putStrLn "bad value"; y
so if x == 5 it should return x, else it should print 'bad value' and return y - how can I do that in haskell ?
edit:
Why this code returns error: "couldn't match expected type bool with actual type IO bool" ?
canTest :: String -> IO Bool
canTest x = if x == "5" then return True
else do putStrLn "bad value"; return False
test x y = if canTest x then x
else y
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使双方具有相同的类型,即
IO String
。为此,您需要使用return
将值提升到 monad 中,即现在
return x
的类型为IO String
,因此else 分支中的do
块。You need to make both sides have the same type, namely
IO String
. For this you need to usereturn
to lift the values into the monad, i.e.Now
return x
has the typeIO String
, and so does thedo
block in the else branch.因为
canTest
有副作用(即进行 I/O),所以它的返回类型是IO Bool
,这有两个含义:您编辑的
test
函数也必须位于 IO monad 中,因为您无法转义 IO。 (除非非常小心地使用unsafePerformIO
)导致
Because
canTest
has side-effects (i.e. does I/O), its return type isIO Bool
, which has two implications:Your edited
test
function must also be in the IO monad, as you cannot escape IO. (Unless very carefully withunsafePerformIO
)Results in