Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 65d5609939
Fetching contributors…

Cannot retrieve contributors at this time

file 873 lines (757 sloc) 30.076 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# OPTIONS_GHC -Wall #-}

#if __GLASGOW_HASKELL__ <= 706
{-# LANGUAGE DoRec #-}
#else
{-# LANGUAGE RecursiveDo #-}
#endif

-- | Event/discrete layer constructed on top of Elerea.
-- The API is largely inspired by reactive-banana.
module FRP.Euphoria.Event
(
-- * Events
  Event
-- ** Creation
, externalEvent
, eachStep
, onCreation
, signalToEvent
-- ** Sampling
, apply
, eventToSignal
-- ** State accumulation
-- | With these functions, any input event occurrence will affect the output
-- immediately, without any delays.
, stepperS
, accumS
, accumSIO
, accumE
, accumEM
, scanAccumE
, scanAccumEM
-- ** Filtering and other list-like operations
, filterE
, justE
, mapMaybeE
, flattenE
, expandE
, withPrevE
, dropE
, dropWhileE
, takeE
, takeWhileE
, partitionEithersE
, leftE
, rightE
, groupByE
, groupWithInitialByE
, groupE
, groupWithInitialE
, splitOnE
, differentE
-- ** Other event operations
, delayE
, dropStepE
, mapEIO
, memoE
, joinEventSignal
, generatorE
-- * Discrete signals
, Discrete
-- ** Sampling 'Discrete's
-- $sampling_discrete

-- ** Accumulation
, stepperD
, stepperDefD
, stepperMaybeD
, justD
, accumD
-- ** Conversion into events
, eachStepD
, changesD
, preservesD
-- ** Other discrete operations
, snapshotD -- broken? crashes?
, memoD
, delayD
, generatorD
, minimizeChanges
, discreteToSignal
, freezeD
, signalToDiscrete
, keepJustsD
, keepDJustsD
-- * Signals
, module FRP.Euphoria.Signal
-- * Application operators
, Apply (..)
-- $app_discrete_maybe
, (<$?>), (<?*?>), (<-*?>), (<?*->)
, EasyApply (..)
-- * Switching
, switchD
, switchDE
, switchDS
, generatorD'
, SignalSet (..)
-- * Evaluation control
, forceD
, forceE
, rnfD
, rnfE
-- * Debugging
-- | Side-effecting trace functions
, traceSignalMaybe
, traceSignalT
, traceEventT
, traceDiscreteT
-- * Testing
, signalFromList
, eventFromList
, networkToList
) where

import Control.Arrow ((&&&))
import Control.Applicative
import Control.DeepSeq
import Control.Monad (join, replicateM)
import Control.Monad.Fix
import Data.Default
import Data.Either (partitionEithers, lefts, rights)
import Data.List (foldl')
import Data.Monoid
import Data.Maybe
import Data.Typeable
import Debug.Trace
import FRP.Euphoria.Signal
import FRP.Elerea.Simple (transfer, externalMulti, effectful1, until, stateful)
import Prelude hiding (until)

-- | @Event a@ represents a stream of events whose occurrences carry
-- a value of @a@. The event can have zero, one or more occurrences
-- in a single network step.
--
-- Two event occurrences are said to be simultaneous iff they are within
-- the same step. Simultaneous occurrences are ordered within a single
-- event stream, but not across different event streams.
newtype Event a = Event (Signal [a])
  deriving (Functor, Typeable)
-- | @Discrete a@ is much like @'Signal' a@, but the user can get notified
-- every time the value may have changed. See 'changesD'.
newtype Discrete a = Discrete (Signal (Bool, a))
  -- The first component indicates if the value may be new.
  -- If it is False, the consumer should avoid evaluating the
  -- second component whenever possible.
  -- FIXME: This trick alone cannot remove all redundant recomputations.
  -- Consider the case where a Discrete is
  -- read every iteration in a fresh SignalGen run.
  deriving (Functor, Typeable)
-- type Behavior a = Signal a

-- | Event streams can be merged together. In case of simultaneous occurrences,
-- occurrences from the left stream comes first.
instance Monoid (Event a) where
  mempty = Event $ pure []
  Event a `mappend` Event b = Event $ (++) <$> a <*> b

infixl 4 <@>, <@

-- | A generalization of @Applicative@ where the lhs and the rhs can have
-- different container types.
class (Functor f, Functor g) => Apply f g where
  (<@>) :: f (a -> b) -> g a -> g b
  (<@) :: f a -> g b -> g a

  f <@ g = const <$> f <@> g

instance Apply Signal Event where
  (<@>) = apply

-- It's difficult to implement this without causing needless recalculation:
--instance Apply Discrete Event where

-- | Create an event that can be triggered as an IO action.
externalEvent :: IO (SignalGen (Event a), a -> IO ())
externalEvent = do
  (gen, trigger) <- externalMulti
  return (Event . fmap reverse <$> gen, trigger)

-- | Transform an event stream using a time-varying transformation function.
--
-- There is also an infix form '<@>'.
apply :: Signal (a -> b) -> Event a -> Event b
apply sig (Event evt) = Event $ map <$> sig <*> evt

-- | Filter an event stream.
filterE :: (a -> Bool) -> Event a -> Event a
filterE cond (Event evt) = Event $ filter cond <$> evt

-- | @stepperS initial evt@ returns a signal whose value is the last occurrence
-- of @evt@, or @initial@ if there has been none.
stepperS :: a -> Event a -> SignalGen (Signal a)
stepperS initial (Event evt) = transfer initial upd evt
  where
    upd [] old = old
    upd occs _ = last occs

-- | @eachStep sig@ is an event that occurs every step, having the same
-- value as @sig@.
eachStep :: Signal a -> Event a
eachStep = Event . fmap (:[])

-- | 'Discrete' version of eachStep.
eachStepD :: Discrete a -> SignalGen (Event a)
eachStepD d = do
  sig <- discreteToSignal d
  return $ eachStep sig

-- | The basic construct to build a stateful signal. @accumS initial evt@
-- returns a signal whose value is originally @initial@. For each occurrence
-- of @evt@ the value of the signal gets updated using the function.
--
-- Example:
--
-- If we have an event stream of numbers, (nums :: Event Int), then
-- we can make a signal that remembers the sum of the numbers seen
-- so far, as follows:
--
-- > accumS 0 $ (+) <$> nums
accumS :: a -> Event (a -> a) -> SignalGen (Signal a)
accumS initial (Event evt) = transfer initial upd evt
  where
    upd occs old = foldl' (flip ($)) old occs

-- | @accumS@ with side-effecting updates.
accumSIO :: a -> Event (a -> IO a) -> SignalGen (Signal a)
accumSIO initial (Event evt) = mfix $ \self -> do
  prev <- delayS initial self
  effectful1 id $ update <$> prev <*> evt
  where
    update prev upds = foldl' (>>=) (return prev) upds

-- | @accumE initial evt@ maintains an internal state just like @accumS@.
-- It returns an event which occurs every time an update happens.
-- The resulting event, once created, will have the same number of
-- occurrences as @evt@ each step.
accumE :: a -> Event (a -> a) -> SignalGen (Event a)
accumE initial (Event evt) = fmap Event $ do
  (_, occs) <- mfix $ \ ~(self, _) -> do
    prev <- delayS initial self
    vs <- memoS $ scanl (flip ($)) <$> prev <*> evt
    return (last <$> vs, tail <$> vs)
  return occs

-- | A useful special case of 'accumE'.
scanAccumE :: s -> Event (s -> (s, a)) -> SignalGen (Event a)
scanAccumE initial ev = (snd <$>) <$> accumE (initial, undefined) (f <$> ev)
  where
    f fn (s, _) = fn s

-- | Monadic version of @accumE@.
accumEM :: s -> Event (s -> SignalGen s) -> SignalGen (Event s)
accumEM initial (Event evt) = fmap Event $ do
  rec
    prevState <- delayS initial (fst <$> state_out)
    state_out <- generatorS $ stateGen <$> prevState <*> evt
  memoS $ snd <$> state_out
  where
    stateGen prev occs = foldr app end occs prev []
    app occ next val history = do
      val' <- occ val
      next val' (val':history)
    end val history = return (val, reverse history)

-- | A useful special case of @accumEM@.
scanAccumEM :: s -> Event (s -> SignalGen (s, a)) -> SignalGen (Event a)
scanAccumEM initial ev = (snd <$>) <$> accumEM (initial, undefined) (f <$> ev)
  where
    f fn (s, _) = fn s

-- | Drops all events in this network step
dropStepE :: Event a -> SignalGen (Event a)
dropStepE ev = do
    initial <- delayS True (pure False)
    memoE $ justE $ discardIf <$> initial <@> ev
    where
        discardIf True _ = Nothing
        discardIf False x = Just x

-- | Converts an event stream of lists into a stream of their elements.
-- All elements of a list become simultaneous occurrences.
flattenE :: Event [a] -> Event a
flattenE (Event evt) = Event $ concat <$> evt

-- | Expand simultaneous events (if any)
expandE :: Event a -> Event [a]
expandE (Event evt) = Event $ f <$> evt
    where
        f [] = []
        f xs = [xs]

-- | Like 'mapM' over events.
mapEIO :: (t -> IO a) -> Event t -> SignalGen (Event a)
mapEIO mkAction (Event evt) = Event <$> effectful1 (mapM mkAction) evt

-- | Memoization of events. See the doc for 'FRP.Elerea.Simple.memo'.
memoE :: Event a -> SignalGen (Event a)
memoE (Event evt) = Event <$> memoS evt

-- | An event whose occurrences come from different event stream
-- each step.
joinEventSignal :: Signal (Event a) -> Event a
joinEventSignal sig = Event $ do
  Event occs <- sig
  occs

-- | Remove occurrences that are 'Nothing'.
justE :: Event (Maybe a) -> Event a
justE (Event evt) = Event $ catMaybes <$> evt

-- | Like 'mapMaybe' over events.
mapMaybeE :: (a -> Maybe b) -> Event a -> Event b
mapMaybeE f evt = justE $ f <$> evt

-- | @onCreation x@ creates an event that occurs only once,
-- immediately on creation.
onCreation :: a -> SignalGen (Event a)
onCreation x = Event <$> delayS [x] (return [])

-- | @delayE evt@ creates an event whose occurrences are
-- same as the occurrences of @evt@ in the previous step.
delayE :: Event a -> SignalGen (Event a)
delayE (Event x) = Event <$> delayS [] x

-- | @withPrevE initial evt@ is an Event which occurs every time
-- @evt@ occurs. Each occurrence carries a pair, whose first element
-- is the value of the current occurrence of @evt@, and whose second
-- element is the value of the previous occurrence of @evt@, or
-- @initial@ if there has been none.
withPrevE :: a -> Event a -> SignalGen (Event (a, a))
withPrevE initial evt = accumE (initial, undefined) $ toUpd <$> evt
  where
    toUpd val (new, _old) = (val, new)

-- | @generatorE evt@ creates a subnetwork every time @evt@ occurs.
generatorE :: Event (SignalGen a) -> SignalGen (Event a)
generatorE (Event evt) = Event <$> generatorS (sequence <$> evt)

-- | @dropE n evt@ returns an event, which behaves similarly to
-- @evt@ except that its first @n@ occurrences are dropped.
dropE :: Int -> Event a -> SignalGen (Event a)
dropE n (Event evt) = Event . fmap fst <$> transfer ([], n) upd evt
    where
        upd occs (_, k)
            | k <= 0 = (occs, 0)
            | otherwise = let
                !k' = k - length occs
                in (drop k occs, k')

-- | @dropWhileE p evt@ returns an event, which behaves similarly to
-- @evt@ except that all its occurrences before the first one
-- that satisfies @p@ are dropped.
dropWhileE :: (a -> Bool) -> Event a -> SignalGen (Event a)
dropWhileE p (Event evt) = Event . fmap fst <$> transfer ([], False) upd evt
  where
    upd occs (_, True) = (occs, True)
    upd occs (_, False) = case span p occs of
      (_, []) -> ([], False)
      (_, rest) -> (rest, True)

-- | Take the first n occurrences of the event and discard the rest.
-- It drops the reference to the original event after
-- the first n occurrences are seen.
takeE :: Int -> Event a -> SignalGen (Event a)
takeE n evt = generalPrefixE (primTakeE n) evt

primTakeE :: Int -> Signal [a] -> SignalGen (Signal (Bool, [a]))
primTakeE n evt = fmap fst <$> transfer ((True, []), n) upd evt
    where
        upd occs (_, k) = ((k > 0, take k occs), k')
            where
                !k' = k - length occs

-- | Take the first occurrences satisfying the predicate and discard the rest.
-- It drops the reference to the original event after
-- the first non-satisfying occurrence is seen.
takeWhileE :: (a -> Bool) -> Event a -> SignalGen (Event a)
takeWhileE p evt = generalPrefixE (primTakeWhileE p) evt

primTakeWhileE :: (a -> Bool) -> Signal [a] -> SignalGen (Signal (Bool, [a]))
primTakeWhileE p evt = memoS $ f <$> evt
    where
        f occs = case span p occs of
          (_, []) -> (True, occs)
          (end, _) -> (False, end)

generalPrefixE
  :: (Signal [a] -> SignalGen (Signal (Bool, [a])))
  -> Event a
  -> SignalGen (Event a)
generalPrefixE prefixTaker (Event evt) = do
    rec
        done <- until $ not . fst <$> active_occs
        prevDone <- delayS False done
        eventSource <- transfer evt upd prevDone
        active_occs <- prefixTaker (join eventSource)
    Event <$> memoS (snd <$> active_occs)
    where
        upd done prev = ifelse done (pure []) prev

        {-# NOINLINE ifelse #-}
        ifelse b x y = if b then x else y

        -- Here we hide an if expression from GHC's optimizer.
        -- If GHC finds this conditional, its "state hack"
        -- transforation turns the definition into:
        --
        -- upd done prev s = if done then [] else prev s
        --
        -- which is a disaster, because now (upd False prev)
        -- doesn't reduce to prev. This means each iteration
        -- the signal gets bigger and more expensive to evaluate.

-- | Split a stream of 'Either's into two, based on tags. This needs to be
-- in SignalGen in order to memoise the intermediate result.
partitionEithersE :: Event (Either a b) -> SignalGen (Event a, Event b)
partitionEithersE (Event eithersS) = (Event . fmap fst &&& Event . fmap snd)
  <$> memoS (partitionEithers <$> eithersS)

-- | Keep occurrences which are Left.
leftE :: Event (Either e a) -> Event e
leftE (Event eithersS) = Event (lefts <$> eithersS)

-- | Keep occurrences which are Right.
rightE :: Event (Either e a) -> Event a
rightE (Event eithersS) = Event (rights <$> eithersS)

-- | @groupByE eqv evt@ creates a stream of event streams, each corresponding
-- to a span of consecutive occurrences of equivalent elements in the original
-- stream. Equivalence is tested using @eqv@.
groupByE :: (a -> a -> Bool) -> Event a -> SignalGen (Event (Event a))
groupByE eqv sourceEvt = fmap snd <$> groupWithInitialByE eqv sourceEvt

-- | @groupWithInitialByE eqv evt@ creates a stream of event streams, each corresponding
-- to a span of consecutive occurrences of equivalent elements in the original
-- stream. Equivalence is tested using @eqv@. In addition, each outer event
-- occurrence contains the first occurrence of its inner event.
groupWithInitialByE :: (a -> a -> Bool) -> Event a -> SignalGen (Event (a, Event a))
groupWithInitialByE eqv sourceEvt = do
    networkE <- justE <$> scanAccumE Nothing (makeNetwork <$> sourceEvt)
    generatorE networkE
    where
        makeNetwork val currentVal
            | maybe False (eqv val) currentVal = (currentVal, Nothing)
            | otherwise = (Just val, Just $ (,) val <$> network val)
        network val = takeWhileE (eqv val) =<< dropWhileE (not . eqv val) sourceEvt

-- | Same as @'groupByE' (==)@
groupE :: (Eq a) => Event a -> SignalGen (Event (Event a))
groupE = groupByE (==)

-- | Same as @groupWithInitialByE (==)@
groupWithInitialE :: (Eq a) => Event a -> SignalGen (Event (a, Event a))
groupWithInitialE = groupWithInitialByE (==)

-- | For each Event () received, emit all 'a' in a list since the last
-- Event () was received. In the case of simultaneous 'a' and '()' in
-- a step, the 'a' are included in the emitted list.
splitOnE :: Event () -> Event a -> SignalGen (Event [a])
splitOnE completeE aE = do
    let inE = (Right <$> aE) `mappend` (Left <$> completeE)
    let f (Left ()) accAs = ([], Just (reverse accAs))
        f (Right a) accAs = (a : accAs, Nothing)
    memoE =<< justE <$> scanAccumE [] (f <$> inE)

-- | @eventToSignal evt@ is a signal whose value is the list of current
-- occurrences of @evt@.
eventToSignal :: Event a -> Signal [a]
eventToSignal (Event x) = x

-- | The inverse of 'eventToSignal'.
signalToEvent :: Signal [a] -> Event a
signalToEvent = Event

-- $sampling_discrete
-- 'Signal's can be sampled using 'apply' or equivalently '<@>'.
-- However, currently there are no corresponding functions for 'Discrete'
-- due to implementation difficulty. To sample a 'Discrete', you need to
-- first convert it into a 'Signal' using 'discreteToSignal'.

-- | @changesD dis@ is an event that occurs when the value of @dis@ may
-- have changed. It never occurs more than once a step.
changesD :: Discrete a -> Event a
changesD (Discrete dis) = Event $ conv <$> dis
  where
    conv (new, x) = if new then [x] else []

-- | Like 'changesD', but uses the current value in the Discrete even if
-- it is not new.
preservesD :: Discrete a -> SignalGen (Event a)
preservesD dis = do
    ev <- onCreation ()
    sig <- discreteToSignal dis
    memoE $ (const <$> sig <@> ev) `mappend` changesD dis

-- | @snapshotD dis@ returns the current value of @dis@.
snapshotD :: Discrete a -> SignalGen a
-- Seems to cause problems with the network. Is the underlying
-- 'snapshot' actually safe?
snapshotD (Discrete a) = snd <$> snapshotS a

-- | Like 'stepperS', but creates a 'Discrete'.
stepperD :: a -> Event a -> SignalGen (Discrete a)
stepperD initial (Event evt) = Discrete <$> transfer (False, initial) upd evt
  where
    upd [] (_, old) = (False, old)
    upd occs _ = (True, last occs)

-- | Use a 'Default' instance to supply the initial value.
stepperDefD :: (Default a) => Event a -> SignalGen (Discrete a)
stepperDefD = stepperD def

-- | Use 'Nothing' to supply the initial value, and wrap the returned
-- type in 'Maybe'.
stepperMaybeD :: Event a -> SignalGen (Discrete (Maybe a))
stepperMaybeD ev = stepperDefD (Just <$> ev)

-- | Given an initial value, filter out the Nothings.
justD :: a -> Discrete (Maybe a) -> SignalGen (Discrete a)
justD initial mD = do
    mE <- preservesD mD
    stepperD initial (justE mE)

-- | Like @accumS@, but creates a 'Discrete'.
accumD :: a -> Event (a -> a) -> SignalGen (Discrete a)
accumD initial (Event evt) = Discrete <$> transfer (False, initial) upd evt
  where
    upd [] (_, old) = (False, old)
    upd upds (_, old) = (True, new)
      where !new = foldl' (flip ($)) old upds

-- | Filter events to only those which are different than the previous event.
differentE :: (Eq a) => Event a -> SignalGen (Event a)
differentE ev = (justE . (f <$>)) <$> withPrevE Nothing (Just <$> ev)
  where
    f :: (Eq a) => (Maybe a, Maybe a) -> Maybe a
    f (new, old) = if new /= old then new else old

instance Applicative Discrete where
  pure x = Discrete $ pure (False, x)
  Discrete f <*> Discrete a = Discrete $ app <$> f <*> a
    where
      app (newFun, fun) (newArg, arg) = (new, fun arg)
        where !new = newFun || newArg

instance Monad Discrete where
  return x = Discrete $ return (False, x)
  Discrete x >>= f = Discrete $ do
    (newX, v) <- x
    let Discrete y = f v
    (newY, r) <- y
    let !new = newX || newY
    return (new, r)

-- | Memoization of discretes. See the doc for 'FRP.Elerea.Simple.memo'.
memoD :: Discrete a -> SignalGen (Discrete a)
memoD (Discrete dis) = Discrete <$> memoS dis

-- | Like 'delayS'.
delayD :: a -> Discrete a -> SignalGen (Discrete a)
delayD initial (Discrete subsequent) = Discrete <$> delayS (True, initial) subsequent

-- | Like 'generatorS'. A subnetwork is only created when the value of the
-- discrete may have changed.
generatorD :: Discrete (SignalGen a) -> SignalGen (Discrete a)
generatorD (Discrete sig) = do
    first <- delayS True $ pure False
    listResult <- generatorS $ networkOnChanges <$> first <*> sig
    stepperD undefined (Event listResult)
    where
        networkOnChanges first (new, gen)
            | first || new = (:[]) <$> gen
            | otherwise = return []

-- | Executes a dynamic 'SignalGen' in a convenient way.
--
-- > generatorD' dis = generatorD dis >>= switchD
generatorD' :: (SignalSet s) => Discrete (SignalGen s) -> SignalGen s
generatorD' dis = generatorD dis >>= switchD

-- | @minimizeChanges dis@ creates a Discrete whose value is same as @dis@.
-- The resulting discrete is considered changed only if it is really changed.
minimizeChanges :: (Eq a) => Discrete a -> SignalGen (Discrete a)
minimizeChanges (Discrete dis) = Discrete . fmap fromJust <$> transfer Nothing upd dis
  where
    upd (False, _) (Just (_, cache)) = Just (False, cache)
    upd (True, val) (Just (_, cache))
      | val == cache = Just (False, cache)
    upd (new, val) _ = Just (new, val)

recordDiscrete :: Discrete a -> SignalGen (Discrete a)
recordDiscrete (Discrete dis) = Discrete . fmap fromJust <$> transfer Nothing upd dis
  where
    upd (False, _) (Just (_, cache)) = Just (False, cache)
    upd new_val _ = Just new_val

-- | Converts a 'Discrete' to an equivalent 'Signal'.
discreteToSignal :: Discrete a -> SignalGen (Signal a)
discreteToSignal dis = discreteToSignalNoMemo <$> recordDiscrete dis

-- | @switchD dis@ creates some signal-like thing whose value is
-- same as the thing @dis@ currently contains.
switchD :: (SignalSet s) => Discrete s -> SignalGen s
switchD dis = recordDiscrete dis >>= basicSwitchD >>= memoizeSignalSet

-- | @switchDS@ selects current @Signal a@ of a 'Discrete'.
--
-- See @switchD@ for a more general function.
switchDS :: Discrete (Signal a) -> SignalGen (Signal a)
switchDS = switchD

-- | @switchDE@ selects the current 'Event' stream contained in a 'Discrete'
--
-- See @switchD@ for a more general function.
switchDE :: Discrete (Event a) -> SignalGen (Event a)
switchDE = switchD

-- | @freezeD fixEvent dis@ returns a discrete whose value is same as
-- @dis@ before @fixEvent@ is activated first. Its value gets fixed once
-- an occurrence of @fixEvent@ is seen.
freezeD :: Event () -> Discrete a -> SignalGen (Discrete a)
freezeD evt dis = do
    dis' <- memoD dis
    now <- onCreation ()
    sig <- discreteToSignal dis'
    initialization <- takeE 1 $ const <$> sig <@> now
    filteredChanges <- switchD =<< stepperD (changesD dis') (mempty <$ evt)
    stepperD (error "freezeD: not initialized") $ initialization `mappend` filteredChanges

-- | Convert a 'Signal' to an equivalent 'Discrete'. The resulting discrete
-- is always considered to \'possibly have changed\'.
signalToDiscrete :: Signal a -> Discrete a
signalToDiscrete x = Discrete $ (,) True <$> x

traceSignalMaybe :: String -> (a -> Maybe String) -> Signal a -> Signal a
traceSignalMaybe loc f sig = do
  v <- sig
  case f v of
    Nothing -> pure v
    Just str -> trace (loc ++ ": " ++ str) $ pure v

traceSignalT :: (Show b) => String -> (a -> b) -> Signal a -> Signal a
traceSignalT loc f = traceSignalMaybe loc (Just . show . f)

traceEventT :: (Show b) => String -> (a -> b) -> Event a -> Event a
traceEventT loc f (Event sig) = Event $ traceSignalMaybe loc msg sig
  where
    msg [] = Nothing
    msg occs = Just $ show (map f occs)

traceDiscreteT :: (Show b) => String -> (a -> b) -> Discrete a -> Discrete a
traceDiscreteT loc f (Discrete sig) = Discrete $ traceSignalMaybe loc msg sig
  where
    msg (True, val) = Just $ show (f val)
    msg (False, _) = Nothing

keepJustsD :: Discrete (Maybe (Maybe a))
           -> SignalGen (Discrete (Maybe a))
keepJustsD tm = do
    emm <- preservesD tm
    stepperD Nothing (justE emm)

keepDJustsD :: Discrete (Maybe (Discrete a))
            -> SignalGen (Discrete (Maybe a))
keepDJustsD dmd =
    fmap (fmap Just) . justE <$> preservesD dmd
    >>= stepperD (return Nothing) >>= switchD

-- $app_discrete_maybe
-- Convenience combinators for working with \''Discrete' a\' and \''Discrete'
-- (Maybe a)\' in applicative style. You can choose the right one by
-- representing what's on the left and right side of the operator with
-- the following rules:
--
-- * \'-' is for Discrete a
--
-- * \'?' is for Discrete (Maybe a)
--
infixl 4 <$?>, <?*?>, <-*?>, <?*->
(<$?>) :: (a -> b) -> Discrete (Maybe a) -> Discrete (Maybe b)
f <$?> valmD = fmap f <$> valmD

(<?*?>) :: Discrete (Maybe (a -> b)) -> Discrete (Maybe a) -> Discrete (Maybe b)
fmD <?*?> valmD = do
    fm <- fmD
    valm <- valmD
    return (fm <*> valm)

(<-*?>) :: Discrete (a -> b) -> Discrete (Maybe a) -> Discrete (Maybe b)
f <-*?> valmD = (fmap <$> f) <*> valmD

(<?*->) :: Discrete (Maybe (a -> b)) -> Discrete a -> Discrete (Maybe b)
fmD <?*-> valD = do
    fm <- fmD
    case fm of
        Just f -> Just . f <$> valD
        Nothing -> return Nothing

infixl 4 <~~>
-- | When using applicative style and mixing @('Discrete' a)@ and
-- @('Discrete' ('Maybe' a))@, EasyApply's \<~~> will attempt to choose the
-- right combinator. This is an experimental idea, and may be more
-- trouble than it's worth in practice.
--
-- GHC will fail to find instances under various circumstances, such
-- as when when anonymous functions are applied to tuples, so you will
-- have to fall back to using explicit combinators.
class EasyApply a b c | a b -> c where
  (<~~>) :: a -> b -> c

instance EasyApply (a -> b) (Discrete a) (Discrete b) where
    (<~~>) = (<$>)
instance EasyApply (Discrete (a -> b)) (Discrete a) (Discrete b) where
    (<~~>) = (<*>)
instance EasyApply (a -> b) (Discrete (Maybe a)) (Discrete (Maybe b)) where
    (<~~>) = (<$?>)
instance EasyApply (Discrete (Maybe (a -> b))) (Discrete (Maybe a)) (Discrete (Maybe b)) where
    (<~~>) = (<?*?>)
instance EasyApply (Discrete (a -> b)) (Discrete (Maybe a)) (Discrete (Maybe b)) where
    (<~~>) = (<-*?>)
instance EasyApply (Discrete (Maybe (a -> b))) (Discrete a) (Discrete (Maybe b)) where
    (<~~>) = (<?*->)

instance EasyApply (Signal (a -> b)) (Event a) (Event b) where
    (<~~>) = apply

-- Some instances which may be less common
instance EasyApply (Maybe (a -> b)) (Discrete a) (Discrete (Maybe b)) where
    Just f <~~> valD = Just . f <$> valD
    Nothing <~~> _ = return Nothing

-- Add more as necessary. TODO the application of some more brainpower
-- should be able to get all possible instances using type-level
-- programming, I think.

-- Evaluation control

-- | Forces the value in a Discrete.
forceD :: Discrete a -> SignalGen (Discrete a)
forceD aD = generatorD $ (\x -> x `seq` return x) <$> aD

-- | Like forceD, but for Event.
forceE :: Event a -> SignalGen (Event a)
forceE aE = generatorE $ (\x -> x `seq` return x) <$> aE

-- | Completely evaluates the value in a Discrete.
rnfD :: (NFData a) => Discrete a -> SignalGen (Discrete a)
rnfD = forceD . fmap force

-- | Like rnfD, but for Event.
rnfE :: (NFData a) => Event a -> SignalGen (Event a)
rnfE = forceE . fmap force

#if !MIN_VERSION_deepseq(1,2,0)
force :: NFData a => a -> a
force x = x `deepseq` x
#endif


--------------------------------------------------------------------------------
-- SignalSet

-- | A class of signal-like types.
class SignalSet a where
    -- | Create a dynamically switched @a@. The returned value doesn't need
    -- to be properly memoized. The user should call `switchD` instead.
    basicSwitchD :: Discrete a -> SignalGen a
    -- | Memoize a signal set.
    memoizeSignalSet :: a -> SignalGen a

instance SignalSet (Signal a) where
    basicSwitchD dis = return $ join $ discreteToSignalNoMemo dis
    memoizeSignalSet = memoS

instance SignalSet (Event a) where
    basicSwitchD dis = return $ joinEventSignal $ discreteToSignalNoMemo dis
    memoizeSignalSet = memoE

instance SignalSet (Discrete a) where
    basicSwitchD dis = return $ join dis
    memoizeSignalSet = memoD

instance (SignalSet a, SignalSet b) => SignalSet (a, b) where
    basicSwitchD dis = (,)
        <$> (basicSwitchD $ fst <$> dis)
        <*> (basicSwitchD $ snd <$> dis)
    memoizeSignalSet (x, y) = (,) <$> memoizeSignalSet x <*> memoizeSignalSet y

instance (SignalSet a, SignalSet b, SignalSet c) => SignalSet (a, b, c) where
    basicSwitchD dis = (,,)
        <$> (basicSwitchD $ e30 <$> dis)
        <*> (basicSwitchD $ e31 <$> dis)
        <*> (basicSwitchD $ e32 <$> dis)
        where
            e30 (a, _, _) = a
            e31 (_, a, _) = a
            e32 (_, _, a) = a
    memoizeSignalSet (x, y, z) =
        (,,) <$> memoizeSignalSet x <*> memoizeSignalSet y <*> memoizeSignalSet z

instance (SignalSet a, SignalSet b, SignalSet c, SignalSet d) =>
        SignalSet (a, b, c, d) where
    basicSwitchD dis = (,,,)
        <$> (basicSwitchD $ e40 <$> dis)
        <*> (basicSwitchD $ e41 <$> dis)
        <*> (basicSwitchD $ e42 <$> dis)
        <*> (basicSwitchD $ e43 <$> dis)
        where
            e40 (a, _, _, _) = a
            e41 (_, a, _, _) = a
            e42 (_, _, a, _) = a
            e43 (_, _, _, a) = a
    memoizeSignalSet (x0, x1, x2, x3) = (,,,)
      <$> memoizeSignalSet x0
      <*> memoizeSignalSet x1
      <*> memoizeSignalSet x2
      <*> memoizeSignalSet x3

instance (SignalSet a, SignalSet b, SignalSet c, SignalSet d, SignalSet e) =>
        SignalSet (a, b, c, d, e) where
    basicSwitchD dis = (,,,,)
        <$> (basicSwitchD $ e50 <$> dis)
        <*> (basicSwitchD $ e51 <$> dis)
        <*> (basicSwitchD $ e52 <$> dis)
        <*> (basicSwitchD $ e53 <$> dis)
        <*> (basicSwitchD $ e54 <$> dis)
        where
            e50 (a, _, _, _, _) = a
            e51 (_, a, _, _, _) = a
            e52 (_, _, a, _, _) = a
            e53 (_, _, _, a, _) = a
            e54 (_, _, _, _, a) = a
    memoizeSignalSet (x0, x1, x2, x3, x4) = (,,,,)
      <$> memoizeSignalSet x0
      <*> memoizeSignalSet x1
      <*> memoizeSignalSet x2
      <*> memoizeSignalSet x3
      <*> memoizeSignalSet x4

-- | discreteToSignal outside the SignalGen monad.
-- A careless use leads to repeated computation.
discreteToSignalNoMemo :: Discrete a -> Signal a
discreteToSignalNoMemo (Discrete x) = snd <$> x

--------------------------------------------------------------------------------
-- Testing

signalFromList :: [a] -> SignalGen (Signal a)
signalFromList list = fmap hd <$> stateful list tl
    where
        hd [] = error "signalFromList: list exhausted"
        hd (x:_) = x

        tl [] = error "signalFromList: list exhausted"
        tl (_:xs) = xs

eventFromList :: [[a]] -> SignalGen (Event a)
eventFromList list = Event <$> signalFromList (list ++ repeat [])

networkToList :: Int -> SignalGen (Signal a) -> IO [a]
networkToList n network = do
    sample <- start network
    replicateM n sample

-- vim: ts=2 sts=2
Something went wrong with that request. Please try again.