<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[Posts on code | Brandon.Si(mmons)]]></title>
  <link href="http://brandon.si/./code/atom.xml" rel="self"/>
  <link href="http://brandon.si/"/>
  <updated>2013-06-10T22:05:51-04:00</updated>
  <id>http://brandon.si/</id>
  <author>
    <name><![CDATA[Brandon Simmons]]></name>
    <email><![CDATA[brandon.m.simmons@gmail.com]]></email>
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[Thinking about an economy of bit flips]]></title>
    <link href="http://brandon.si/code/thinking-about-an-economy-of-bit-flips/"/>
    <updated>2013-03-17T00:25:00-04:00</updated>
    <id>http://brandon.si/code/thinking-about-an-economy-of-bit-flips</id>
    <content type="html"><![CDATA[<p><em>Disclaimer: un-researched, under-educated, fast and loose hacking follows.</em></p>

<hr />

<p>The other day I was thinking about counting in binary and how bits cascade when
incrementing a counter.</p>

<pre><code>000
001
010
011
100
</code></pre>

<p>I wondered: what if each bit flip was very "expensive", for the hardware say?
Are there other methods we could use that woud result in a "cheaper" increment
operation, by avoiding those costly carries?</p>

<p>First, here's a little bit of boring code that we'll use below to print a list
of Ints as padded binary, and some requisite imports:</p>

<pre><code>import Data.Bits
import Data.Word
import Numeric
import Text.Printf
import Data.Char

prettyPrintBits :: (Integral i, Show i)=&gt; [i] -&gt; IO ()
prettyPrintBits = mapM_ putStrLn . prettyListBits

prettyListBits :: (Integral i, Show i)=&gt; [i] -&gt; [String]
prettyListBits l = map (printPadded . toBin) l where
    toBin i = showIntAtBase 2 intToDigit i ""
    printPadded = printf ("%0"++width++"s")
    width = show $ ceiling $ logBase 2 $ (+1) $ fromIntegral $ maximum l
</code></pre>

<p>Anyway I started playing with this by hand, with a 3-bit example, and drawing
funny pictures like these:</p>

<p><img src="/post_images/2013-03-17-thinking-about-an-economy-of-bit-flips/sketch.png" alt="notebook sketch" /></p>

<p>On the left is a table with the cost, in bit-flips, to increment a binary
counter to that number, from the previous.</p>

<p>Then (in the middle of the pic above) I drew an undirected graph with edges
connecting the numbers that differed by only a single bit (lots of symmetry
there, no?); so what we'd like to do is walk that graph without repeating, to
cycle through all the 3-bit combinations as "efficiently" as possible.</p>

<p>After doodling for a second I found a nice symmetrical path through the graph,
and wrote the numbers we pass through in sequence (on the right side of the pic
above).</p>

<p>Okay, but can we write a program to generate that sequence? And generalize it?</p>

<h2>Generating Sequences</h2>

<p>After I marked the bit-flip locations in the "bit-economical" binary sequence,
I noticed the pattern from top to bottom is the same as what we'd use to build
a <a href="http://brandon.si/code/building-a-tree-from-an-ordered-list/">binary tree from an ordered list</a>,
numbered from the bottom up.</p>

<p>Furthermore glancing back to my original table of "increment costs" I noticed
they follow the same pattern; it turns out we can use a few simple bitwise
operations on a normal binary count to enumerate all n-bit numbers with
optimally-efficient bit flips. The algorithm is:</p>

<ul>
<li>start the sequence at 0</li>
<li>for a count 0,1,2.. do

<ul>
<li>find the difference (<code>XOR</code>) of adjacent numbers</li>
<li>find the number of <code>1</code>s in the result (<code>POPCNT</code>)</li>
<li>flip the bit at that offset to get to the next number in the sequence</li>
</ul>
</li>
</ul>


<p>Here's an implementation in haskell that represents an infinite (sort of)
efficient bit count:</p>

<pre><code>lazyBits :: [Word]
lazyBits = scanl complementBit 0 bitsToFlip where
    ns = [0..] :: [Word]
    bitsToFlip = zipWith (\x-&gt; subtract 1 . popCount . xor x) ns $ tail ns
</code></pre>

<p>We can play with this &amp; pretty-print the result:</p>

<pre><code>*Main Text.Printf&gt; take (2^3) $ lazyBits 
[0,1,3,2,6,7,5,4]
*Main Text.Printf&gt; prettyPrintBits $ take (2^3) $ lazyBits 
000
001
011
010
110
111
101
100
</code></pre>

<h3>Aside: Applications and variations</h3>

<p>This is similar to
<a href="http://brandon.si/code/cracking-a-lock-in-haskell-with-the-de-bruijn-sequence-pt-1/">de Bruijn sequences</a>
and I'm sure this sort of sequence has some interesting applications. For
instance just as with de Bruijn sequences I could see this being useful in
cracking an imaginary lock consisting of toggling push-button digits.</p>

<p>But most real locks like that have buttons that lock in place and have a single
"reset" button. To model those we could do something similar to what we just
did, only we'd want to study a directed graph where we only ever have edges
resulting from flipping a <code>0</code> to a <code>1</code>, and all numbers have an edge back to
<code>0</code>.</p>

<h2>Back to thinking about counting</h2>

<p>We've gotten side-tracked a bit. We started wanting to find a more efficient
binary number system for incrementing, but is that what we got?</p>

<p>Well, no. In particular we have no algorithm for incrementing an arbitrary
number in our sequence. For instance, given only the number <code>010</code> we have
no way (that I've been able to figure out) of knowing that the left-most bit
should be flipped. In other words we need <em>some</em> amount of state to determine
the next bit to be flipped. At least that's my assumtion.</p>

<h3>Comparison</h3>

<p>One thing we <em>do</em> have is a method for comparing numbers in the sequence,
something that's pretty much essential if you want to do anything with a
counter.</p>

<p>Here is some code to do just that, defined here in terms of bit strings (as
output by <code>prettyListBits</code>); I haven't figure out a clever set of bitwise ops
to do this, and have a somewhat foggy idea of why this works:</p>

<pre><code>compareNums :: String -&gt; String -&gt; Ordering
compareNums [] [] = EQ
compareNums ('0':as) ('0':bs) = compareNums as bs
compareNums ('1':as) ('1':bs) = invert $ compareNums as bs
    where invert EQ = EQ
          invert GT = LT
          invert LT = GT
compareNums (a:_) (b:_) = compare a b
compareNums _ _ = error "this assumes 0-padded, aligned numbers"
</code></pre>

<h3>Counting, amortized increment cost, state</h3>

<p>So how much does it really cost <em>on average</em> to increment an arbitrary number
in the usual binary number system?  We know it's more than one, but we need a
function from bit length to average cost.</p>

<p>To do that efficiently we'll once again use the pattern we discovered above
when we sketched out a 3-bit example. Looking at the way the different costs
break down we have:</p>

<pre><code>4 operations at cost 1
2 operations at cost 2
1 operation  at cost 3
</code></pre>

<p>...out of a total of <code>8 - 1</code> increment operations, so the average cost is:</p>

<pre><code>(4*1 + 2*2 + 1*3) / (8 - 1) = 1.5714
</code></pre>

<p>So a general function for <code>b</code> bits would look like:</p>

<pre><code>amortizedIncrCost :: Integer -&gt; Double
amortizedIncrCost b = avgd $ sum $ zipWith (*) (iterate (2*) 1) [b,b-1 ..1]
    where avgd n = (fromIntegral n) / (2^b - 1)
</code></pre>

<p>We'd like to know how this behaves as our number of bits <code>b</code> approaches
infinity. We could take the limit of the function, but who knows how to do
that, so let's just experiment:</p>

<pre><code>*Main&gt; amortizedIncrCost 3
1.5714285714285714
*Main&gt; amortizedIncrCost 4
1.7333333333333334
*Main&gt; amortizedIncrCost 8
1.968627450980392
*Main&gt; amortizedIncrCost 16
1.9997558556496529
*Main&gt; amortizedIncrCost 32
1.9999999925494194
*Main&gt; amortizedIncrCost 64
2.0
</code></pre>

<p>Seems quite clearly to approach 2 as we exceed the accuracy of our <code>Double</code>,
i.e. the average cost to increment an arbitrary-size binary counter is
two bit flips. Interesting!</p>

<p>Remember above how we mentioned our counting system required some additional
state to determine the next bit to flip? Well a single bit is the smallest
unit of state we know about; therefore even if we could figure out how to
determine bit-flips with a single bit of state, or could derive a way of
calculating the offset from the number itself, we'd still never be able to
do better than two bit-flips per increment.</p>

<p>This is probably all pretty obvious
<a href="http://en.wikipedia.org/wiki/Information_theory">information theory</a>
stuff, but was a fun little diversion.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Using GHC's RebindableSyntax for a dynamic state "Fauxnad"]]></title>
    <link href="http://brandon.si/code/using-ghcs-rebindablesyntax-for-a-dynamic-state-fauxnad/"/>
    <updated>2013-02-10T22:14:00-05:00</updated>
    <id>http://brandon.si/code/using-ghcs-rebindablesyntax-for-a-dynamic-state-fauxnad</id>
    <content type="html"><![CDATA[<p>I just learned about GHC's <code>RebindableSyntax</code> extension from
<a href="http://www.reddit.com/r/haskell/comments/16zrsp/generalizing_do_notation/">chrisdoner's thread on reddit</a>
and wanted to play around with scratching a couple itches I've had. In this
post I'll illustrate using <code>RebindableSyntax</code> to allow us to use haskell's
<code>do</code> notation in a State-monad-like construction, in which our state type is
allowed to change (I've played with this idea
<a href="http://brandon.si/code/a-state-monad-with-dynamically-typed-state/">previously</a>).</p>

<p>The dynamic state construction looks like the traditional <code>State</code>, but with
separate types for input and output state:</p>

<pre><code>{-# LANGUAGE DeriveFunctor, MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}
newtype DynState s1 s2 a = DynState { runState :: s1 -&gt; (a,s2) }
    deriving Functor

get :: DynState s s s
get = DynState $ \s-&gt; (s,s)

put :: s -&gt; DynState x s ()
put = DynState . const . (,) ()

modify :: (s1 -&gt; s2) -&gt; DynState s1 s2 ()
modify = DynState . fmap ((,) ())
</code></pre>

<p>We can compose these by defining a (for the moment, very verbose) function
<code>dynStateBind</code>. Interestingly, this is actually easier to understand IMHO than
the <code>State</code> monad because the type signature makes explicit the fact that our
lambda-bound state <code>s1</code> is the <em>initial</em> state value that we run the
construction on:</p>

<pre><code>infixl 1 `dynStateBind` 
dynStateBind :: DynState s1 s2 a -&gt; (a -&gt; DynState s2 s3 b) -&gt; DynState s1 s3 b
dynStateBind x f = DynState $ \s1-&gt; let ~(a,s2) = runState x s1
                                     in runState (f a) s2
</code></pre>

<p>We also need stand-ins for <code>(&gt;&gt;)</code> and <code>return</code>:</p>

<pre><code>-- It would be nice if &gt;&gt; inherited default instances in terms of bind, as in
-- an instance declaration
infixl 1 `dynThen`
dynThen :: DynState s1 s2 a -&gt; DynState s2 s3 b -&gt; DynState s1 s3 b
dynThen x y = x `dynStateBind` \_ -&gt;  y

dynReturn :: a -&gt; DynState s s a
dynReturn a = DynState $ \s-&gt; (a,s)
</code></pre>

<p>So then we can use all the nonsense above as follows:</p>

<pre><code>{-# LANGUAGE RebindableSyntax #-}
module Main
    where

import Prelude -- since RebindableSyntax implies NoImplicitPrelude
import DynState

-- avoid lame "Not in scope: `ifThenElse'"
ifThenElse b x y | b = x
                 | otherwise = y
-- oops, infinite loop fail!
--ifThenElse b x y = if b then x else y 

test :: DynState Int Int String
test = let (&gt;&gt;=)  = dynStateBind
           (&gt;&gt;)   = dynThen
           return = dynReturn
        in do i &lt;- get             -- state :: Int
              put (even i, show i) -- state :: (Bool, String)
              (b,i_str) &lt;- get
              put (i+1)            -- state :: Int
              if b then return "uh oh, even!"
                   else return $ "pre-incremented: "++i_str
</code></pre>

<p>If we want to we can even enrich our bind and add some machinery to support
composing traditional <code>StateT</code> computations with our dynamic state:</p>

<pre><code>-- | a silly class to support comosing regular State monad computations with
-- dynamic state computations.
class Stateful n s1 s2 | n -&gt; s1 s2 where
    expand :: n a -&gt; DynState s1 s2 a

instance Stateful (DynState s1 s2) s1 s2 where
    expand = id

instance Stateful (M.StateT s Identity) s s where
    expand = DynState . M.runState

-- category with bind sort of situation...
polyDynStateBind :: (Stateful x s1 s2, Stateful y s2 s3)=&gt; x a -&gt; (a -&gt; y b) -&gt; DynState s1 s3 b
polyDynStateBind x f = expand x `dynStateBind` fmap expand f

-- | convert a dynamic stateful computation into the usual State monad, so we
-- can compose it with normal state computations
flatten :: DynState s s a -&gt; M.State s a
flatten = M.state . runState 
</code></pre>

<h2>Zippers</h2>

<p>At some point while working on <a href="http://brandon.si/code/zippo/">zippo</a> (you<br/>
should check out <a href="http://hackage.haskell.org/packages/archive/lens/3.8.5/doc/html/Control-Lens-Zipper.html">this</a>
instead) I made up detailed notes on a DSL for zipper operations that I wished
I could shoe-horn into <code>do</code> or <code>Arrow</code> notation, but never quite could.</p>

<p>Lost the notes, but the idea would be to have bind expose the "focus" of the
zipper and allow motions down and up to be sequenced nicely with minimal
boilerplate, as in the state monad. Maybe I'll find those and fill in this
section properly.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[dilly.js: a library for loops with delays in JavaScript]]></title>
    <link href="http://brandon.si/code/dilly-dot-js-a-library-for-loops-with-delays-in-javascript/"/>
    <updated>2012-10-09T22:29:00-04:00</updated>
    <id>http://brandon.si/code/dilly-dot-js-a-library-for-loops-with-delays-in-javascript</id>
    <content type="html"><![CDATA[<p>I've released a <a href="https://github.com/jberryman/dilly.js">new library</a>
for writing sort of idiomatic-looking loops with delays in javascript. This was
motivated by <a href="http://jberryman.github.com/fly-mis/">this</a>
work in which I was implementing an algorithm/simulation;
I wanted the code to be readable as straighforward loops, but I needed
a delay for the visual portion.</p>

<p>Here is an example of its usage:</p>

<pre><code>withDelay(1000).endingWith(other_stuff)                  
    .for("x",1,2)                // range: 1, 2
        .for("y",1,3 , 8)        // range(with step of 2): 1, 3, 5, 7
            .for("z",['a','b'])  // foreach: 'a', 'b'
                .do(function(){ 
                    console.log(this.var("x"), 
                                this.var("y"), 
                                this.var("z"));
                 });
</code></pre>

<p>The inner <code>do</code> block runs with a one-second delay between executions.</p>

<p>You can pick up the code with</p>

<pre><code>$ git clone https://github.com/jberryman/dilly.js.git
</code></pre>

<p>The design is actually much closer conceptually to list comprehensions.
Also, I'm fairly certain that the approach I took is far messier than
necessary, but I was suffering from elegant coder's block.</p>

<p>Send me any pull requests or bug reports you have.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Making your zipper disappear with Zippo]]></title>
    <link href="http://brandon.si/code/making-your-zipper-disappear-with-zippo/"/>
    <updated>2012-09-17T20:43:00-04:00</updated>
    <id>http://brandon.si/code/making-your-zipper-disappear-with-zippo</id>
    <content type="html"><![CDATA[<p>I've finally had a chance to look at how my new lens-based, power-packed,
minimal zipper library <a href="http://hackage.haskell.org/package/zippo-0.1">zippo</a>
looks when compiled, and initial results are pleasing!</p>

<p>For example, here is a silly zipper operation that increments the nodes
of a sort-of tree:</p>

<pre><code>module Main where

import Control.Category((&gt;&gt;&gt;))
import Data.Lens.Zipper
import Data.Yall.Lens

data Tree a = Br { _lBranch :: NodeBr a
                 , _rBranch :: NodeBr a }
            deriving Show

data NodeBr a = NodeBr { _node :: a }
    deriving Show

-- START BOILERPLATE
lBranch = lens _lBranch (\(Br _ r) l-&gt; Br l r)
rBranch = lens _rBranch (\(Br l _) r-&gt; Br l r)
node = lens _node $ const NodeBr
-- END BOILERPLATE

-- example data:
t = Br (NodeBr 1 ) (NodeBr 3 )

-- zipper operations
incNode = moveP node &gt;&gt;&gt; modf (+1) &gt;&gt;&gt; moveUp
zops = zipper &gt;&gt;&gt; moveP lBranch &gt;&gt;&gt; incNode &gt;&gt;&gt; moveUp &gt;&gt;&gt; 
        moveP rBranch &gt;&gt;&gt; incNode &gt;&gt;&gt; close

main = print $ zops t
</code></pre>

<p>When compiled with</p>

<pre><code>ghc --make -fforce-recomp -ddump-simpl -dsuppress-all -O2 SimpleExample.hs
</code></pre>

<p>this produces the following beautiful core:</p>

<pre><code>zops =
  \ w_s2uY -&gt;
    case w_s2uY of _ { Br ww_s2v0 ww1_s2v1 -&gt;
    Br
      (NodeBr
         (case ww_s2v0 of _ { NodeBr ds_d16N -&gt;
          plusInteger ds_d16N incNode2
          }))
      (NodeBr
         (case ww1_s2v1 of _ { NodeBr ds_d16N -&gt;
          plusInteger ds_d16N incNode2
          }))
    }
</code></pre>

<p>Alakazam! Some more complex examples also produced nice code with performance
identical to the most straightforward equivalent definition.</p>

<h3>TODOs</h3>

<p>The above gave me an opportunity to test a handful of rewrite rules which I'm
excited about, but first I need to tie up some loose ends to get this useful:</p>

<ol>
<li>create some combinators that together with (<code>&gt;&gt;&gt;</code>) form a nice DSL for
zipper operations, including nice support for partial lens "Alternative-like"
statements</li>
<li>get the underlying lens library situation sorted out:

<ul>
<li>either add automatic lens deriving TH to <a href="http://hackage.haskell.org/package/yall">yall</a> (not looking forward to this), or...</li>
<li>see if I can convince ekmett to modify <a href="http://hackage.haskell.org/package/lens">lens</a> in some clever way to support my use case (not optimistic about this)</li>
<li>use <a href="http://hackage.haskell.org/package/data-lens">data-lens</a> now that it does "partial lenses"</li>
</ul>
</li>
<li>look at some of Oleg's zipper stuff for actual applications of zippers to guide development</li>
</ol>


<p>Leave a note if you have questions or ideas for me.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[simple-actors 0.4.0: a few interesting design bits]]></title>
    <link href="http://brandon.si/code/simple-actors-0-dot-4-0-a-few-interesting-design-bits/"/>
    <updated>2012-08-22T21:21:00-04:00</updated>
    <id>http://brandon.si/code/simple-actors-0-dot-4-0-a-few-interesting-design-bits</id>
    <content type="html"><![CDATA[<p><a href="http://hackage.haskell.org/package/simple-actors">simple-actors</a>
is my library for more structured concurrent programming based
on the <a href="http://en.wikipedia.org/wiki/Actor_model">Actor model</a>.
It's been a fun vehicle for exploring concurrent
semantics, and an opportunity to solve some tricky API design problems in
pretty clever ways. I want to present a handful of these problems, and the
solutions I came up with, below.</p>

<p><em>Short digression:</em> I love distributed systems, but this library has nothing to
do with distributed programming. Also performance.</p>

<h2>Goals and Constraints</h2>

<p>To frame things, these were more or less the goals of the library design:</p>

<ul>
<li>create a friendly, light-weight (hopefully intuitive), non-leaky, non-brittle eDSL for concurrent algorithms</li>
<li>base functionality on existing typeclasses and abstractions wherever possible</li>
<li>employ an economy of concepts; avoid creating new things requiring names and
explanations, unless absolutely necessary</li>
</ul>


<p>And here are the three little case-studies.</p>

<h2>Eschew channel abstraction</h2>

<p>The first challenge was how to keep the abstraction for message routing as
minimal as possible. Ideally we would like our <code>spawn</code> function to return
a token (we call it a "Mailbox") that is used by other actors as a reference
for sending messages to the <code>spawn</code>-ed actor:</p>

<pre><code>spawn :: Behavior a -&gt; Action (Mailbox a)
</code></pre>

<p>But then how do you handle two actors sending messages to each other? Or an
actor sending itself a message for that matter?</p>

<pre><code>do a &lt;- spawn $ senderTo b
   b &lt;- spawn $ senderTo a
   c &lt;- spawn $ senderTo c
   send a ...
</code></pre>

<p>The sequencing of monadic actions in a <code>do</code> block make scoping an issue here,
so what can we do?</p>

<p>Should we insist that actors like <code>a</code> and <code>b</code> pass their mailboxes explicitly
in messages? But then we'd have to build implicit access to an actor's
own Mailbox <em>into our Behavior abstraction</em> since we can't even define a
<code>Behavior</code> closed over it's own <code>Mailbox</code>, as in <code>c</code> above.</p>

<p>What about separating channel creation and spawning into two distinct functions,
where we spawn a <code>Behavior</code> listening <em>on a channel</em>? But then we have to
decide what should happen when two actors are spawned on the same channel, etc.
Let's just not do any of that.</p>

<p>The solution turns out to be a matter of knowing the right classes, in
particular the exotic <code>MonadFix</code> (read up on it
<a href="http://www.haskell.org/haskellwiki/MonadFix">here</a>). Combined with GHC's lovely
<code>DoRec</code> extension, our crisis resolves itself, allowing:</p>

<pre><code>{-# LANGUAGE DoRec #-}
do rec a &lt;- spawn $ senderTo b
       b &lt;- spawn $ senderTo a
       c &lt;- spawn $ senderTo c
   send a ...
</code></pre>

<p>IMHO this looks much tastier than
<a href="http://www.erlang.org/doc/getting_started/conc_prog.html#id66766">what erlang has to offer</a>.</p>

<h2>Mailbox should support a rich set of transformations</h2>

<p>A second design challenge has been to try to realize the full potential of
our internal "chan" pair type (of which <code>Mailbox</code> only is exposed) in terms
of CT-ish transformations supported.</p>

<p>Some background: a concurrent <code>Chan</code> separated into a pair of "read" and
"write" sides is attractive, because it suggests the possibility for
the "read" end to have a <code>Functor</code> instance, while the "write" side suggests
it could be a <a href="http://hackage.haskell.org/package/contravariant">contravariant functor</a>, supporting an operation:</p>

<pre><code>contramap :: (Contravariant f)=&gt; (b -&gt; a) -&gt; f a -&gt; f b
</code></pre>

<p>Consider how <code>Control.Concurrent.Chan</code> doesn't permit that possibility.</p>

<p>Initial versions of <a href="http://hackage.haskell.org/package/chan-split">chan-split</a> (used internally)
defined Functor and Contravariant instances, supported with a clumsy GADT
representation which looked like, e.g.</p>

<pre><code>data InChan i where
    InChan :: (i -&gt; a) -&gt; C.Chan a -&gt; InChan i
</code></pre>

<p>This was removed when I realized I could support the operations ("read" / "write")
and powerful transformations that weren't possible before, by defining <code>Mailbox</code>
as simply a wrapper <em>around <code>writeChan c</code> itself</em>. Likewise, our internal "write
end" becomes a wrapped <code>readChan c</code> action:</p>

<pre><code>newtype Mailbox a = Mailbox (a -&gt; IO ())
newtype Messages a = Messages (IO a)
</code></pre>

<p>Here are the <a href="http://hackage.haskell.org/packages/archive/simple-actors/0.4.0/doc/html/Control-Concurrent-Actors.html#g:8">nice transformations</a>
we've defined so far; more are possible. <em>N.B.</em>
that these don't add anything in terms of expressiveness to the actor model,
i.e. we could envision doing the same sort of thing trivially with actors.</p>

<h2>Getting more expressive with join patterns</h2>

<p>The final and most recent design bit I wanted to share address the problem
of "synchronization".</p>

<p>Consider how you would go about trying to definean actor that "pairs up" inputs
received from a pair of actors; your solution would involve an actor that kept
a possibly-ever-expanding buffer of unmatched messages. This is a limitation
inherent in the actor model, and leads to needless tragedy like erlang's
<a href="http://ndpar.blogspot.com/2010/11/erlang-explained-selective-receive.html">"selective receive"</a>.</p>

<p>What we want is to be able to define an actor that can block on multiple
channels. How do we do that without weird channel abstractions creeping
into our API?</p>

<p>I'd been mulling around the idea of creating a completely new beast, sort
of dual to an Actor that could read from arbitrary chans, and feed inputs
one-at-a-time to an actor. A "Reducer" or something.</p>

<p>Luckily I had a better idea while reading about process calculi, in particular
the <a href="http://join.inria.fr/">join calculus</a>. The solution makes the library formally more expressive
while removing complexity from the UI and leaving the semantics of behaviors
and message-passing unchanged!</p>

<p>The trick was to come up with a class that would allow the spawn function to
introduce assymetry between spawned <code>Behavior</code> inputs and <code>Mailbox</code>es, i.e.
we create a <code>spawn</code> that can return multiple <code>Mailbox</code>es which are "joined"
to a single <code>Behavior</code> input in the background:</p>

<pre><code>sumTuple :: Behavior (Int, Int)

do b &lt;- spawn sumTuple
   send b (4, 1) 
   -- or. like magic...
   (b1, b2) &lt;- spawn sumTuple
   send b1 4
   send b2 1
</code></pre>

<p>See <a href="http://hackage.haskell.org/packages/archive/simple-actors/0.4.0/doc/html/Control-Concurrent-Actors.html#t:Sources">the docs</a>
for a few other examples of the new behavior of <code>spawn</code>. The <code>Sources</code> class
works using TypeFamilies and an associated <code>Joined</code> type that is a <em>function
of the return type</em> of <code>spawn</code>. Use the source.</p>

<h1>Meta</h1>

<p>Is this sort of post interesting, or is this kind of case study too esoteric
or domain-specific to be useful? Let me know. And if you have ideas of your
own or want to help with performance testing, do a</p>

<pre><code>git clone https://github.com/jberryman/simple-actors.git
</code></pre>

<p>and play with it.</p>
]]></content>
  </entry>
  
</feed>
