haskellreactive-banana

Reactive Banana: Change status in data


Starting from the Counter example in Reactive Banana Wx that uses a normal Int to keep the counter status:

let networkDescription :: forall t. Frameworks t => Moment t () 
    networkDescription = do
    eup   <- event0 bup   command
    edown <- event0 bdown command

    let
        counter :: Behavior t Int
        counter = accumB 0 $ ((+1) <$ eup) `union` (subtract 1 <$ edown)

    sink output [text :== show <$> counter]

network <- compile networkDescription
actuate network

how can I replace and update the Int counter with a more generic data like:

data Counter = Counter {
     count :: Int
 } deriving (Show)

let
    counter :: Behavior t Counter
    counter = accumB Counter { count = 0 } $ ??????

sink output [text :== show <$> count counter]

I don't know how to refer to the internal count function with something like this:

count = count mycounter + 1

Any idea?


Solution

  • The type of accumB is:

    accumB :: a -> Event t (a -> a) -> Behavior t a
    

    So if you want to define a Behavior t Counter with it you need to use events that carry Counter -> Counter functions:

    -- For the sake of convenience...
    overCount :: (Int -> Int) -> Counter -> Counter
    overCount f c = c { count = f (count c) }
    
    counter = accumB Counter { count = 0 } $
        (overCount (+1) <$ eup) `union` (overCount (subtract 1) <$ edown)