Collecting IO outputs into list

2019-04-26 20:12发布

How can I issue multiple calls to SDL.pollEvent :: IO Event until the output is SDL.NoEvent and collect all the results into a list?

In imperative terms something like this:

events = []
event = SDL.pollEvent
while ( event != SDL.NoEvent ) {
        events.add( event )
        event = SDL.pollEvent
}

5条回答
闹够了就滚
2楼-- · 2019-04-26 20:38

Using these stubs for Event and pollEvent

data Event = NoEvent | SomeEvent
  deriving (Show,Eq)

instance Random Event where
  randomIO = randomRIO (0,1) >>= return . ([NoEvent,SomeEvent] !!)

pollEvent :: IO Event
pollEvent = randomIO

and a combinator, borrowed and adapted from an earlier answer, that stops evaluating the first time the predicate fails

spanM :: (Monad m) => (a -> Bool) -> m a -> m [a]
spanM p a = do
  x <- a
  if p x then do xs <- spanM p a
                 return (x:xs)
         else return [x]

allows this ghci session, for example:

*Main> spanM (/= NoEvent) pollEvent 
[SomeEvent,SomeEvent,NoEvent]
查看更多
forever°为你锁心
3楼-- · 2019-04-26 20:41

You can use monadic lists:

import Control.Monad.ListT (ListT)
import Control.Monad.Trans.Class (lift) -- transformers, not mtl
import Data.List.Class (takeWhile, repeat, toList)
import Prelude hiding (takeWhile, repeat)

getEvents :: IO [Event]
getEvents = 
    toList . takeWhile (/= NoEvent) $ do
        repeat ()
        lift pollEvent :: ListT IO Event

ListT from the "List" package on hackage.

查看更多
仙女界的扛把子
4楼-- · 2019-04-26 20:53

You could use something like:

takeWhileM :: (a -> Bool) -> IO a -> IO [a]
takeWhileM p act = do
  x <- act
  if p x
    then do
      xs <- takeWhileM p act
      return (x : xs)
    else
      return []

Instead of:

do
  xs <- takeWhileM p act
  return (x : xs)

you can also use:

liftM (x:) (takeWhileM p act) yielding:

takeWhileM :: (a -> Bool) -> IO a -> IO [a]
takeWhileM p act = do
  x <- act
  if p x
    then liftM (x:) (takeWhileM p act)
    else return []

Then you can use: takeWhileM (/=SDL.NoEvent) SDL.pollEvent

查看更多
Rolldiameter
5楼-- · 2019-04-26 20:53

i eventually stumbled over this code snippet in an actual SDL game from hackage

getEvents :: IO Event -> [Event] -> IO [Event]
getEvents pEvent es = do
  e <- pEvent
  let hasEvent = e /= NoEvent
  if hasEvent
   then getEvents pEvent (e:es)
   else return (reverse es)

thanks for your answers btw!

查看更多
smile是对你的礼貌
6楼-- · 2019-04-26 20:56

James Cook was so kind to extend monad-loops with this function:

unfoldWhileM  :: Monad  m => (a -> Bool) -> m a -> m [a]

used with SDL:

events <- unfoldWhileM (/= SDL.NoEvent) SDL.pollEvent
查看更多
登录 后发表回答