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

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

问题描述

我创建了一个组合框,它通过 xmlWidget 转换为 comboBox > castTocomboBox 现在我想获取活动项目的文本或索引。问题是,如果我使用 comboBoxGetActive 函数,它会返回一个 IO Int 结果,我需要知道我怎么能获取 Int 值。我尝试了解monads,所以我可以理解在这种情况下可以做些什么,但我似乎不明白。我很感激我能得到的所有帮助。我应该提及我使用 Glade gtk2hs

解决方案

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

  do 
x< - somethingThatReturnsIO
somethingElseThatReturnsIO $ pureFunction x

没有办法获得 Int,除了在IO Monad中做其他事情。



单数条款中,上面的代码解析成

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

>> =操作符(发音为bind)将IO Int转换为Int的神奇功效,但它拒绝给出直接对你。它只会将该值作为参数传递给另一个函数,并且该函数必须返回IO中的另一个值。冥想几分钟的IO monad绑定类型,你可能会开悟:

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

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



(当然,这里有臭名昭着的unsafePerformIO,但在你的级别上如果你使用它,那么你就错了。)



(实际上,desugaring对于失败的模式匹配来说相当复杂,但是你可以假装我写的是真的)


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

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

In monad terms, the above code desugars into

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

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

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.

(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天全站免登陆