我正在尝试编写一个简单的基于命令行的反射游戏,它会提示用户在随机时间后按回车键,然后输出反应时间。我正在使用基于此示例的 reactimate:https ://wiki.haskell.org/Yampa/reactimate 我的代码按照我的意图运行得非常好:
module Main where
import Control.Monad
import Data.IORef
import Data.Time.Clock
import System.Random
import FRP.Yampa
main :: IO ()
main = do
startTime <- getCurrentTime
startTimeRef <- newIORef startTime
randomTime <- randomRIO (0, 10)
reactimate helloMessage (sense startTimeRef) sayNow (randomTimePassed randomTime)
playerTime <- getCurrentTime
playerTimeRef <- newIORef playerTime
s <- getLine --programm will wait here
reactimate doNothing (sense playerTimeRef) endMessage (enterPressed s)
now <- getCurrentTime
let reactionTime = now `diffUTCTime` playerTime in putStr (show reactionTime)
helloMessage :: IO ()
helloMessage = putStrLn "Press Enter as quickly as possible when I say so..."
randomTimePassed :: Double -> SF () Bool
randomTimePassed r = time >>> arr (>r)
sayNow :: Bool -> Bool -> IO Bool
sayNow _ x = when x (putStrLn "NOW!") >> return x
doNothing :: IO ()
doNothing = return ()
enterPressed :: String -> SF () Bool --this is not how I want it to be
enterPressed s = arr (\_ -> s == "")
endMessage :: Bool -> Bool -> IO Bool
endMessage _ x = when x (putStr "You reacted in: ") >> return x
sense :: IORef UTCTime -> Bool -> IO (Double, Maybe ())
sense timeRef _ = do
now <- getCurrentTime
lastTime <- readIORef timeRef
writeIORef timeRef now
let dt = now `diffUTCTime` lastTime
return (realToFrac dt, Just ())
但是对于我在代码中标记的按回车部分,它根本没有真正使用 FRP。由于程序只是等待 getLine 终止,然后立即结束反应循环。所以它几乎只是使用 IO Monad 而不是 FRP。有没有办法重构信号函数enterPressed
,使其以“FRPish”的方式工作?或者在使用reactimate时这根本不可能?