什么是等待并检测Haskell中的按键的简单方法? [英] What is a simple way to wait for and then detect keypresses in Haskell?
问题描述
我对Haskell很新,所以我正在寻找一种简单的方法来检测按键,而不是使用 getLine
。
如果有人知道任何图书馆或者一些伎俩,那就太好了!
如果有更好的地方如果你不想阻止,你可以使用 code> hReady 来检测一个键是否被按下。这对于想要程序运行的游戏很有用,并且在发生游戏时暂停游戏就可以进行按键操作。
这是一个便利功能:
ifReadyDo :: Handle - > IO a - > IO(也许a)
ifReadyDo hnd x = hReady hnd>> = f
其中f True = x>> = return。只要
f _ = return Nothing
可以这样使用:
stdin`ifReadyDo` getChar
返回一个 Maybe
即如果按下了一个键,并且
Nothing code>否则。
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.
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.
这篇关于什么是等待并检测Haskell中的按键的简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!