开发者

How to take out a value out of a monad in Haskell?

开发者 https://www.devze.com 2023-04-02 23:56 出处:网络
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.

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
        开发者_JS百科    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.


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
          -- ...


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号