Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a simple way to wait for and then detect keypresses in Haskell?

I'm pretty new to Haskell, so I'm looking for a simple-ish way to detect keypresses, rather than using getLine.

If anyone knows any libraries, or some trick to doing this, it would be great!

And if there is a better place to ask this, please direct me there, I'd appreciate it.

like image 416
TaslemGuy Avatar asked Oct 08 '10 22:10

TaslemGuy


1 Answers

If you don't want blocking you can use hReady to detect whether a key has been pressed yet. This is useful for games where you want the program to run and pick up a key press whenever it has happened without pausing the game.

Here's a convenience function I use for this:

ifReadyDo :: Handle -> IO a -> IO (Maybe a)
ifReadyDo hnd x = hReady hnd >>= f
   where f True = x >>= return . Just
         f _    = return Nothing

Which can be used like this:

stdin `ifReadyDo` getChar

Returning a Maybe that is Just if a key was pressed and Nothing otherwise.

like image 84
Ollie Saunders Avatar answered Sep 24 '22 08:09

Ollie Saunders