English 中文(简体)
在Haskell中等待然后检测按键的简单方法是什么?
原标题:What is a simple way to wait for and then detect keypresses in Haskell?

我对Haskell很陌生,所以我正在寻找一种简单的方法来检测按键,而不是使用getLine

如果有人知道任何图书馆,或者知道一些这样做的技巧,那就太棒了!

如果有更好的地方问这个问题,请指引我去那里,我会很感激的。

最佳回答

如果您不想阻止,可以使用hReady来检测是否按下了某个键。这对于您希望程序运行并在不暂停游戏的情况下随时按键的游戏非常有用。

以下是我用于此操作的便利功能:

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

可以这样使用:

stdin `ifReadyDo` getChar

返回一个<code>Maybe</code>,即<code>如果按下了键,则返回<code>Just</code>,否则返回<code>Nothing</code>。

问题回答
import System.IO

main :: IO ()
main = do
  hSetBuffering stdin NoBuffering
  x <- getChar
  putStrLn ("You pressed: " ++ [x])

我不知道这什么时候能保证奏效。将终端置于“原始”模式是一个依赖于系统的过程。但它对我来说适用于Linux上的GHC6.12.1。





相关问题
Euler Problem in Haskell -- Can Someone Spot My Error

I m trying my hand at Euler Problem 4 in Haskell. It asks for that largest palindrome formed by multiplying two three-digit numbers. The problem was simple enough, and I thought my Haskell-fu was up ...

How does foldr work?

Can anybody explain how does foldr work? Take these examples: Prelude> foldr (-) 54 [10, 11] 53 Prelude> foldr (x y -> (x+y)/2) 54 [12, 4, 10, 6] 12.0 I am confused about these executions....

Efficient queue in Haskell

How can I efficiently implement a list data structure where I can have 2 views to the head and end of the list, that always point to a head a tail of a list without expensive calls to reverse. i.e: ...

Problem detecting cyclic numbers in Haskell

I am doing problem 61 at project Euler and came up with the following code (to test the case they give): p3 n = n*(n+1) `div` 2 p4 n = n*n p5 n = n*(3*n -1) `div` 2 p6 n = n*(2*n -1) p7 n = n*(5*n -3)...

Ways to get the middle of a list in Haskell?

I ve just started learning about Functional Programming, using Haskel. I m slowly getting through Erik Meijer s lectures on Channel 9 (I ve watched the first 4 so far) and in the 4th video Erik ...

haskell grouping problem

group :: Ord a => [(a, [b])] -> [(a, [b])] I want to look up all pairs that have the same fst, and merge them, by appending all the list of bs together where they have the same a and discarding ...

Closest equivalent to subprocess.communicate in Haskell

I want to do a popen() / python s subprocess.communicate from Haskell - start a program, give it stdin, and get its stdout/stderr. What s the most direct / Haskellish way to do this?

热门标签