TODO
-----
0.4
- allow destructuring using UndecidableInstances (see mockup) on spawn, allowing for new, awesome synchronization semantics!
- make that also work with Behaviors of arbitrary input types using new GHC generics!
Later:
- performance tuning / benchmarking:
+ look at interface file: ghc -ddump-hi Control/Concurrent/Actors.hs -O -c
+ remove current PRAGMA
- close browser and everything, do a fake quick benchmark to get clock info
- be more controlled about the source lists (do once before defaultMain), use 'evaluate'
- run with +RTS -s and make sure everything is 0
- see if case-based nil is better
- get accurate baseline comparison between actors and set
- use INLINABLE
- test again with SPECIALIZE instead
- try adding INLINE to all with higher-order args (or higher-order newtype wrappers)
and make sure our LHS looks good for inlining
- specialize `Action i (Behavior i)` or allow lots of unfolding... ? Optimize those loops, somehow. Rewrite rules?
- take a look at threadscope for random tree test
- look at "let floating" and INLINEABLE to get functions with "fully-applied (syntactically) LHS"
- compare with previous version (cp to /tmp to use previous version)
- get complete code coverage into simple test module
- interesting solution to exit detection:
http://en.wikipedia.org/wiki/Huang%27s_algorithm
- dynamically-bounded chans, based on number of writers to control
producer/consumer issues? Possibly add more goodies to chan-split
see: http://hackage.haskell.org/package/stm-chans
- look at what Functor/Contravariant for read/write ends, and corresponding
natural transformations those allow suggest about limits of Actor model
and investigate inverse of Actors (Reducers?)
- create an experimental Collectors sub-module
- investigate ways of positively influencing thread scheduling based on
actor work agenda?
- export some more useful Actors and global thingies
- 'loop' which keeps consuming (is this provided by a class?)
- function returning an actor to "load balance" inputs over multiple
actors
- an actor that sends a random stream?
- a pre-declared Mailbox for IO?
Eventually:
- some sort of exception handling technique (using actors?)
- abilty to launch an actor that automatically "replicates" if its chan needs more
consumers. This should probably be restricted to an `Action i ()` that we
repeat.
- can we automatically throttle producers on an Actor system level,
optimizing message flow with some algorithm?
- provide an "adapter" for amazon SQS, allowing truly distributed message
passing
- investigate erlang-style selective receive (using Alternative?)
- consider: combining TChans, where values are popped off when available,
for chan-split?
- look at ways we can represent network IO as channels to interface with
this. E.g:
- https://github.com/ztellman/aleph
- http://akka.io/ (scala remote actors lib)
- http://www.zeromq.org/intro:read-the-manual
- interface to amazon SQS
- http://msgpack.org/
- "shared memory" approaches?
- cloudhaskell, haskell-mpi, etc. see:
http://stackoverflow.com/questions/8362998/distributed-haskell-state-of-the-art-in-2011
-Behavior -> enumeratee package translator (and vice versa)
(maybe letting us use useful enumerators)
...also now pipes, conduits, etc. etc.
- study ambient/join/fusion calculi for clues as to where it's really at
CHAN TYPES
==========
By defining our Mailbox as the bare "send" operation we get a very convenient
way of defining contravariant instance, without all the overhead we had before,
while ALSO now supporting some great natural transformations on Mailboxes &
Messages.
We use this newtype to get 'Contravariant' for free, possibly revealing other
insights:

>typeSendera=Op(IO())a>>mailbox::(a->IO())->Mailboxa>mailbox=Mailbox.Op>>runMailbox::Mailboxa->a->IO()>runMailbox=getOp.sender>>mkMailbox::InChana->Mailboxa>mkMailbox=mailbox.writeChan>>mkMessages::OutChana->Messagesa>mkMessages=Messages.readChan>>-- | One can 'send' a messages to a @Mailbox@ where it will be processed>-- according to an actor\'s defined 'Behavior'>newtypeMailboxa=Mailbox{sender::Sendera}>deriving(Contravariant)

We don't need to expose this thanks to the miracle of MonadFix and recursive do,
but this can be generated via the NewSplitChan class below if the user imports
the library:

>newtypeMessagesa=Messages{readMsg::IOa}>deriving(Functor)>>-- Not sure how to derive this or if possible:>instanceSplitChanMailboxMessageswhere>readChan=readMsg>writeChan=runMailbox>>instanceNewSplitChanMailboxMessageswhere>newSplitChan=(mkMailbox***mkMessages)`fmap`newSplitChan

For Mailboxes we can define all transformations associated with Cartesian and
CoCartesian (from 'categories') but where the category is Dual (->), i.e. the
order of the transformation is flipped.
I don't know if/how these precisely fit into an existing class, but for now here
are a handful of useful combinators:

ACTIONS
=======
Functionality is based on our underlying type classes, but users shouldn't need
to import a bunch of libraries to get basic Behavior building functionality.

>infixl3<.|>

>-- | Sequence two @Behavior@s. After the first 'yield's the second takes over,>-- discarding the message the former was processing. See also the 'Monoid'>-- instance for @Behavior@.>-- >-- > b <.|> b' = b `mappend` constB b'>(<.|>)::Behaviori->Behaviori->Behaviori>b<.|>b'=b`mappend`constBb'

The 'yield' function is so named because it is "relinquishing control", i.e. I
think the name reminds of the functionality of and mappend (the last input
is passed along) and also has the meaning "quit".
Its similarity (or not) to the 'enumerator' function of the same same may be a
source of confusion (or the opposite)... I'm not sure.

>-- | Return the message received to start this 'Action' block. /N.B/ the value>-- returned here does not change between calls in the same 'Action'.>-->-- > received = ask>received::Actionii>received=ask

>-- | Send a message asynchronously. This can be used to send messages to other>-- Actors via a 'Mailbox', or used as a means of output from the Actor system>-- to IO since the function is polymorphic.>-- >-- > send b = liftIO . writeChan b>send::(MonadIOm,SplitChancx)=>ca->a->m()>sendb=liftIO.writeChanb

>infixr1<->>>-- | Like 'send' but supports chaining sends by returning the Mailbox.>-- Convenient for initializing an Actor with its first input after spawning,>-- e.g.>-->-- > do mb <- 0 <-> spawn foo>(<->)::(MonadIOm,SplitChancx)=>a->m(ca)->m(ca)>a<->mmb=mmb>>=\mb->sendmba>>returnmb

FORKING AND RUNNING ACTORS:
===========================

>-- | Like 'spawn' but allows one to specify explicitly the channel from which>-- an actor should take its input. Useful for extending the library to work>-- over other channels.>spawnReading::(MonadIOm,SplitChanxc)=>ci->Behaviori->m()>spawnReadingstr=liftIO.void.forkIO.actorRunner>whereactorRunnerb=>readChanstr>>=runBehaviorStepb>>=F.mapM_actorRunner

RUNNING ACTORS
--------------
These work in IO, returning () when the actor finishes with done/mzero:

>-- | Run a @Behavior ()@ in the main thread, returning when the computation>-- exits.>runBehavior_::Behavior()->IO()>runBehavior_b=runBehaviorb[(),()..]>>-- | run a 'Behavior' in the IO monad, taking its \"messages\" from the list.>runBehavior::Behaviora->[a]->IO()>runBehaviorb(a:as)=runBehaviorStepba>>=F.mapM_(`runBehavior`as)>runBehavior__=return()

FORKING ACTORS
--------------

>-- | Fork an actor performing the specified 'Behavior'. /N.B./ an actor >-- begins execution of its 'headBehavior' only after a message has been >-- received; for sending an initial message to an actor right after 'spawn'ing>-- it, ('<|>') can be convenient.>-->-- See also 'spawn_'.>spawn::(MonadIOm)=>Behaviori->m(Mailboxi)>spawnb=do>(m,s)<-liftIOnewSplitChan>spawnReadingsb>returnm>>-- | Fork a looping computation which starts immediately. Equivalent to>-- launching a @Behavior ()@ and another 'Behavior' that sends an infinite stream of>-- ()s to the former\'s 'Mailbox'.>spawn_::(MonadIOm)=>Behavior()->m()>spawn_=liftIO.void.forkIO.runBehavior_

USEFUL GENERAL BEHAVIORS
========================

>-- | Prints all messages to STDOUT in the order they are received,>-- 'yield'-ing /immediately/ after @n@ inputs are printed.>printB::(Shows,Eqn,Numn)=>n->Behaviors>printB=contramap(unlines.return.show).putStrB

We want to yield right after printing the last input to print. This lets us
compose with signalB for instance:
write5ThenExit = putStrB 5 `mappend` signalB c
and the above will signal as soon as it has printed the last message. If we try
to define this in a more traditional recursive way the signal above would only
happen as soon as the sixth message was received.
For now we allow negative

>-- | Like 'printB' but using @putStr@.>putStrB::(Eqn,Numn)=>n->BehaviorString>putStrB0=mempty--special case when called directly w/ 0>putStrBn=Receive$do>s<-received>liftIO$putStrs>guard(n/=1)>return$putStrB(n-1)

>-- | Sends a @()@ to the passed chan. This is useful with 'mappend' for>-- signalling the end of some other 'Behavior'.>-->-- > signalB c = Receive (send c () >> yield)>signalB::(SplitChancx)=>c()->Behaviori>signalBc=Receive(sendc()>>yield)

>-- | A @Behavior@ that discard its first input, returning the passed Behavior>-- for processing subsequent inputs. Useful with 'Alternative' or 'Monoid'>-- compositions when one wants to ignore the leftover 'yield'ed message.>-->-- > constB = Receive . return>constB::Behaviori->Behaviori>constB=Receive.return