Haskell 单子 IO

发布于 2024-11-16 06:02:00 字数 297 浏览 5 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

晌融 2024-11-23 06:02:00

您位于此处的 IO Monad 内部,因此每当您编写“绑定”箭头 <- 时,右侧的内容都必须是 IO 操作。所以简短的答案是,您不想在值 x 上使用 <-

现在,您似乎想为列表中的每个元素而不是单个元素调用 print_matrix。在这种情况下,我认为 Macke 是在正确的轨道上,但我会使用 mapM_ 代替:

mapM_ (putStr . print_matrix . fst) x

应该可以解决问题。

原因是您明确表示您想要一次一个 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 value x.

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:

mapM_ (putStr . print_matrix . fst) x

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 of putStr itself.

清旖 2024-11-23 06:02:00

听起来 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文