从外部网络采样行为

Phi*_*ous 10 io haskell frp reactive-banana sodiumfrp

由于钠已被作者弃用,我正试图将我的代码移植到reactive-banana.然而,两者之间似乎存在一些不协调,以至于我很难过度使用.

例如,在钠中很容易检索行为的当前值:

retrieve :: Behaviour a -> IO a
retrieve b = sync $ sample b
Run Code Online (Sandbox Code Playgroud)

我不知道如何在反应性香蕉中这样做

(我想要这个的原因是因为我试图将行为导出为dbus属性.可以从其他dbus客户端查询属性)

编辑:替换"民意调查"一词,因为它具有误导性

Phi*_*ous 0

答案似乎是“有可能”。

Sample对应于valueB,但没有直接等同于sync

然而,它可以在execute的帮助下重新实现:

module Sync where

import Control.Monad.Trans
import Data.IORef
import Reactive.Banana
import Reactive.Banana.Frameworks

data Network = Network { eventNetwork :: EventNetwork
                       , run :: MomentIO () -> IO ()
                       }

newNet :: IO Network
newNet = do
    -- Create a new Event to handle MomentIO actions to be executed
    (ah, call) <- newAddHandler
    network <- compile $ do
        globalExecuteEV <- fromAddHandler ah
        -- Set it up so it executes MomentIO actions passed to it
        _ <- execute globalExecuteEV
        return ()
    actuate network
    return $ Network { eventNetwork = network
                     , run = call -- IO Action to fire the event
                     }

-- To run a MomentIO action within the context of the network, pass it to the
-- event.
sync :: Network -> MomentIO a -> IO a
sync Network{run = call} f = do
    -- To retrieve the result of the action we set up an IORef
    ref <- newIORef (error "Network hasn't written result to ref")
    -- (`call' passes the do-block to the event)
    call $ do
        res <- f
        -- Put the result into the IORef
        liftIO $ writeIORef ref res
    -- and read it back once the event has finished firing
    readIORef ref

-- Example
main :: IO ()
main = do
    net <- newNet -- Create an empty network
    (bhv1, set1) <- sync net $ newBehavior (0 :: Integer)
    (bhv2, set2) <- sync net $ newBehavior (0 :: Integer)
    set1 3
    set2 7
    let sumB = (liftA2 (+) bhv1 bhv2)
    print =<< sync net (valueB sumB)
    set1 5
    print =<< sync net (valueB sumB)
    return ()
Run Code Online (Sandbox Code Playgroud)