将 IO Int 转换为 Int [英] Converting IO Int to Int

查看:55
本文介绍了将 IO Int 转换为 Int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个组合框,将 xmlWidget 转换为 comboBoxcastTocomboBox 函数,现在我想获取文本或活动项目的索引.问题是,如果我使用 comboBoxGetActive 函数,它会返回一个 IO Int 结果,我需要知道如何获取 Int 值.我试图阅读关于 monad 的内容,以便我能够理解在这种情况下人们可以做什么,但我似乎不明白.我很感激我能得到的所有帮助.我应该提到我使用 Gladegtk2hs.

I've created a combobox from converting a xmlWidget to a comboBox with the function castTocomboBox and now I want to get the text or the index of the active item. The problem is that if I use the comboBoxGetActive function it returns an IO Int result and I need to know how can I obtain the Int value. I tried to read about monads so I could understand what one could do in a situation like this but I don't seem to understand. I appreciate all the help I can get. I should probably mention that I use Glade and gtk2hs.

推荐答案

作为一般规则,您可以这样写:

As a general rule you write something like this:

do
   x <- somethingThatReturnsIO
   somethingElseThatReturnsIO $ pureFunction x

没有办法从IO Int"中取出Int",除非在 IO Monad 中做其他事情.

There is no way to get the "Int" out of an "IO Int", except to do something else in the IO Monad.

在monad术语中,上面的代码脱糖为

In monad terms, the above code desugars into

somethingThatReturnsIO >>= (x -> somethingElseThatReturnsIO $ pureFunction x)

>>="运算符(发音为bind")具有将IO Int"转换为Int"的魔力,但它拒绝将那个 Int 直接提供给您.它只会将该值作为参数传递给另一个函数,并且该函数必须在IO"中返回另一个值.思考 IO monad 的绑定类型几分钟,你可能会有所启发:

The ">>=" operator (pronounced "bind") does the magic of converting the "IO Int" into an "Int", but it refuses to give that Int straight to you. It will only pass that value into another function as an argument, and that function must return another value in "IO". Meditate on the type of bind for the IO monad for a few minutes, and you may be enlightened:

>>= :: IO a -> (a -> IO b) -> IO b

第一个参数是comboBoxGetActive"返回的初始IO Int"值.第二个是一个函数,它接受 Int 值并将其转换为其他一些 IO 值.因此,您可以处理 Int,但这样做的结果永远不会脱离 IO monad.

The first argument is your initial "IO Int" value that "comboBoxGetActive" is returning. The second is a function that takes the Int value and turns it into some other IO value. Thus you can process the Int, but the results of doing so never escape from the IO monad.

(当然还有臭名昭著的unsafePerformIO",但就您的知识水平而言,您可能可以肯定,如果您使用它,那么您就做错了.)

(Of course there is the infamous "unsafePerformIO", but at your level of knowledge you may be certain that if you use it then you are doing it wrong.)

(实际上,为了允许失败的模式匹配,脱糖要复杂得多.但你可以假装我写的是真的)

(Actually the desugaring is rather more complicated to allow for failed pattern matches. But you can pretend what I wrote is true)

这篇关于将 IO Int 转换为 Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆