如何从 Haskell 中的 monad 中取出值?

发布于 2024-12-02 20:25:15 字数 545 浏览 2 评论 0原文

有没有办法从 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 技术交流群。

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

发布评论

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

评论(2

尽揽少女心 2024-12-09 20:25:15

你不应该以这种方式退出 IO monad(除了 unsafePerformIO 函数),但你仍然可以在其中使用你的函数:

process :: MonadIO m => m ()
process = do
          elems <- getAllThings
          let smth = doSomeThingWithThings elems
          -- ...

You are not supposed to exit IO monad this way (except unsafePerformIO function), but you can still use your function inside it:

process :: MonadIO m => m ()
process = do
          elems <- getAllThings
          let smth = doSomeThingWithThings elems
          -- ...
辞旧 2024-12-09 20:25:15

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 statement return put things inside a monad. So either you can call you other function after getting elems and before return or where ever you are calling getAllThings you can use extract the value using <- from the monad and pass it to your function

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