Haskell 单子 IO
compute fp = do
text <- readFile fp
let (a,b) = sth text
let x = data b
--g <- x
putStr $ print_matrix $ fst $ head $ x
当我只获得第一个元素但我想对列表中的所有元素执行此操作时,它会起作用。 当我写 g<- xi 时,无法匹配预期类型“IO t0” 实际类型 [([[Integer]], [[Integer]])]
compute fp = do
text <- readFile fp
let (a,b) = sth text
let x = data b
--g <- x
putStr $ print_matrix $ fst $ head $ x
It works when i get only first element but i want do this for all element on the list of pair.
When i write g<- x i got Couldn't match expected type `IO t0'
with actual type [([[Integer]], [[Integer]])]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您位于此处的 IO Monad 内部,因此每当您编写“绑定”箭头
<-
时,右侧的内容都必须是 IO 操作。所以简短的答案是,您不想在值x
上使用<-
。现在,您似乎想为列表中的每个元素而不是单个元素调用 print_matrix。在这种情况下,我认为 Macke 是在正确的轨道上,但我会使用 mapM_ 代替:
应该可以解决问题。
原因是您明确表示您想要一次一个
putStr
每个元素,但您不关心putStr
本身的结果。You're inside the IO Monad here, so any time you write a "bind" arrow
<-
, the thing on the right side has to be an IO operation. So the short answer is, you don't want to use<-
on the valuex
.Now, it looks like you want to call print_matrix for each element of a list rather than a single element. In that case I think Macke is on the right track, but I would use mapM_ instead:
should do the trick.
The reason is that you are explicitly saying you want to
putStr
each element, one at a time, but you don't care about the result ofputStr
itself.听起来 mapM 可能适合您的要求:
Monad a =>; (b→ac)→ [b]-> a [c]
它用于将 monadic 函数应用于列表,并在 monad 中返回列表
It sounds like mapM might fit your bill:
Monad a => (b -> a c) -> [b] -> a [c]
It's used to apply a monadic function to a list, and get a list back, in the monad