如何从 Haskell 中的 monad 中取出值?
有没有办法从 monad 中取出“东西”?
我正在开发一个游戏,现在我正在尝试了解数据库。我发现 happstack
非常好,但我拿不到东西。
例如,我有这个函数(希望你熟悉 happstack
),
getAllThings :: MonadIO m => m [Thing]
getAllThings = do
elems <- query GetThings
return elems
所以我得到 m [Things]
,但我不能在我的模型中使用它!例如,
doSomeThingWithThings :: [Thing] -> Something
我用谷歌搜索了这个,但什么也没找到。
Is there any way to take "things" out of a monad?
I am developing a game, and I am now trying to understand about databases. I found happstack
really nice, but I can't get the thing.
For example, I have this function (hope you are familiar with happstack
)
getAllThings :: MonadIO m => m [Thing]
getAllThings = do
elems <- query GetThings
return elems
So I get m [Things]
, but I can't use this in my model! For instance
doSomeThingWithThings :: [Thing] -> Something
I googled this and I found nothing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不应该以这种方式退出 IO monad(除了
unsafePerformIO
函数),但你仍然可以在其中使用你的函数:You are not supposed to exit IO monad this way (except
unsafePerformIO
function), but you can still use your function inside it:在
elems <- query GetThings
之后,elems 是[Thing]
所以 do 里面的<-
是关于从 monad 中获取东西(称为绑定)手术)。最后一个语句return
将内容放入 monad 中。因此,您可以在获取 elems 之后和return
之前调用其他函数,或者在调用getAllThings
时,您可以使用<-
提取值code> 从 monad 并将其传递给您的函数After
elems <- query GetThings
the elems is[Thing]
so<-
inside do is about getting things out of monad (called bind operation). The last statementreturn
put things inside a monad. So either you can call you other function after getting elems and beforereturn
or where ever you are callinggetAllThings
you can use extract the value using<-
from the monad and pass it to your function