gpt4 book ai didi

haskell - 如何回顾前一刻

转载 作者:行者123 更新时间:2023-12-01 02:07:11 25 4
gpt4 key购买 nike

我每时每刻都在读取按钮的状态(无论是否按下):

readButton :: IO Boolean
readButton = ...

main = do
(add, fire) <- newAddHandler
network <- compile (desc add)
actuate network
forever $ do
buttonState <- readButton
fire buttonState

desc addButtonEvent = do
eButtonState <- fromAddHandler addButtonEvent
...

所有读取状态都存储在网络描述desc中的eButtonState中。

当当前时刻的状态为1,而前一时刻的状态为0时,按钮被认为是新按下的。所以,如果事件序列是一个列表,函数应该这样写:

f :: [Bool] -> Bool
f (True:False:_) = True
f _ = False

我想把这个函数应用到eButtonState 上,这样我就可以知道按钮是否被按下了。

有可能吗?你会怎么做?如果有更好或更通用的想法或方法来实现这一目标,我将不胜感激。

最佳答案

这是一种方式(这是一个可运行的演示):

import Reactive.Banana
import Reactive.Banana.Frameworks
import Control.Monad
import Control.Applicative -- Needed if you aren't on GHC 7.10.

desc addDriver = do
-- Refreshes the button state. Presumably fired by external IO.
eButtonDriver <- fromAddHandler addDriver
let -- Canonical repersentation of the button state.
bButtonState = stepper False eButtonDriver
-- Observes the button just before changing its state.
ePreviousState = bButtonState <@ eButtonDriver
-- Performs the test your f function would do.
newlyPressed :: Bool -> Bool -> Bool
newlyPressed previous current = not previous && current
-- Applies the test. This works because eButtonDriver and
-- ePreviousState are fired simultaneously.
eNewlyPressed = unionWith newlyPressed
ePreviousState eButtonDriver
-- The same but more compactly, without needing ePreviousState.
{-
eNewlyPressed = newlyPressed <$> bButtonState <@> eButtonDriver
-}
reactimate (print <$> eNewlyPressed)

main = do
(addDriver, fireDriver) <- newAddHandler
network <- compile (desc addDriver)
actuate network
-- Demo: enter y to turn the button on, and any other string to
-- turn it off.
forever $ do
buttonState <- (== "y") <$> getLine
fireDriver buttonState

注意事项:

  • 事件是短暂的,行为是永久的 是决定您是否需要行为或事件流的通用规则。在这种情况下,您需要查看按钮在更新之前的状态,以确定它是否是新更新的。那么,自然要做的事情就是用行为 (bButtonState) 表示按钮状态,该行为由外部触发的事件 (eButtonDriver) 更新。
  • 有关组合器正在做什么的详细信息,请参阅 Reactive.Banana.Combinators .
  • 有关 reactive-banana 中事件和行为更新时间的细则,请参阅 this question .
  • 根据您要执行的操作,changes功能可能会有用。请注意文档中提到的与之相关的注意事项。

关于haskell - 如何回顾前一刻,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31645256/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com