<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Conal Elliott &#187; mutant</title>
	<atom:link href="http://conal.net/blog/tag/mutant/feed" rel="self" type="application/rss+xml" />
	<link>http://conal.net/blog</link>
	<description>Inspirations &#38; experiments, mainly about denotative/functional programming in Haskell</description>
	<lastBuildDate>Thu, 25 Jul 2019 18:15:11 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=4.1.17</generator>
	<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=conal&amp;popout=1&amp;url=http%3A%2F%2Fconal.net%2Fblog%2F&amp;language=en_US&amp;category=text&amp;title=Conal+Elliott&amp;description=Inspirations+%26amp%3B+experiments%2C+mainly+about+denotative%2Ffunctional+programming+in+Haskell&amp;tags=blog" type="text/html" />
	<item>
		<title>Functional reactive partner dancing</title>
		<link>http://conal.net/blog/posts/functional-reactive-partner-dancing</link>
		<comments>http://conal.net/blog/posts/functional-reactive-partner-dancing#comments</comments>
		<pubDate>Tue, 12 Feb 2008 06:16:10 +0000</pubDate>
		<dc:creator><![CDATA[Conal]]></dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[applicative functor]]></category>
		<category><![CDATA[arrow]]></category>
		<category><![CDATA[bot]]></category>
		<category><![CDATA[dance]]></category>
		<category><![CDATA[FRP]]></category>
		<category><![CDATA[functional reactive programming]]></category>
		<category><![CDATA[functor]]></category>
		<category><![CDATA[lead/follow]]></category>
		<category><![CDATA[mutant]]></category>

		<guid isPermaLink="false">http://conal.net/blog/posts/functional-reactive-partner-dancing/</guid>
		<description><![CDATA[This note continues an exploration of arrow-friendly formulations of functional reactive programming. I refine the previous representations into an interactive dance with dynamically interchanging roles of follow and lead. These two roles correspond to the events and reactive values in the (non-arrow) library Reactive described in a few previous posts. The post ends with some [&#8230;]]]></description>
				<content:encoded><![CDATA[<!-- 

Title: Functional reactive partner dancing

Tags: functional reactive programming, FRP, bot, mutant, dance, lead/follow, arrow, functor, applicative functor

URL: http://conal.net/blog/posts/functional-reactive-partner-dancing/

-->

<!-- references -->

<!-- teaser -->

<p><a href=http://www.theage.com.au/news/Technology/Robots-offer-a-hand-on-the-ballroom-floor/2005/06/09/1118123948570.html><img class=illustration src="http://conal.net/images/misc/dancing_robot.jpg" title= "Takahiro Takeda dances with the Partner Ballroom Dance Robot. Photo: AFP." align="right"></a>
This note continues an exploration of arrow-friendly formulations of functional reactive programming.  I refine the previous representations into an <em>interactive dance</em> with dynamically interchanging roles of <em>follow</em> and <em>lead</em>.  These two roles correspond to the events and reactive values in the (non-arrow) library <a href="http://haskell.org/haskellwiki/Reactive" title="Wiki page for the Reactive library">Reactive</a> described in a few previous posts.  The post ends with some examples.</p>

<p>The code described (with documentation and examples) here may be found in the new, experimental library <strong><a href="http://haskell.org/haskellwiki/Bot" title="Wiki page for the Bot library">Bot</a></strong> (which also covers <a href="http://conal.net/blog/posts/functional-reactive-chatter-bots/" title="Blog post: &quot;Functional reactive chatter-bots&quot;">mutant-bots and chatter-bots</a>).</p>

<p><span id="more-17"></span></p>

<h2>Dancing with Mealy machines</h2>

<p>As mentioned in a <a href="http://conal.net/blog/posts/functional-reactive-chatter-bots/" title="Blog post: &quot;Functional reactive chatter-bots&quot;">previous post</a>, Mealy-style automata (&#8220;bots&#8221;) can be given the following type:</p>

<pre><code>a -&gt; (b, a -&gt; (b, a -&gt; (b, ...)))
</code></pre>

<p>where <code>a</code> and <code>b</code> are the types of inputs and outputs, respectively.  The essence of Mealy machines is the alternation of <em>consuming</em> and <em>producing</em> values.  The type ensures that exactly one output is delivered per input.  In recursive form,</p>

<pre><code>newtype a `MutantBot` b = Mutant (a -&gt; (b, a `MutantBot` b))
</code></pre>

<p>which is a special case of Ross Paterson&#8217;s <a href="http://hackage.haskell.org/cgi-bin/hackage-scripts/package/arrows" title="Haskell package: arrows"><code>Automaton</code> arrow transformer</a>.</p>

<p>These bots do nothing until prompted by an external partner.  What kind of thing is that partner?  Unlike our bots, it must have the ability to take initiative, i.e., to produce a value without itself being prompted.  So we might say that the partner is <em>leading</em>, while the bot is <em>following</em> (or <em>acting</em> and <em>reacting</em>, or <em>generative</em> and <em>receptive</em>).</p>

<p>Once the partner has provided a value, the bot can then provide a reponse.  After the bot&#8217;s reponse, there will be another value from the partner.  Once this dance has begun, the roles of <em>lead</em> and <em>follow</em> are no longer static but rather trade back and forth fluidly.</p>

<p>We&#8217;ve seen the type of the bot:</p>

<pre><code>a -&gt; (b, a -&gt; (b, a -&gt; (b, ...)))
</code></pre>

<p>What is the type of the partner who can dance Lead to the bot&#8217;s Follow?  Initially, while the bot waits for a value (follows), the partner provides one (leads).  After that first step, the roles reverse.</p>

<pre><code>(a, b -&gt; (a, b -&gt; (a, b -&gt; ...)))
</code></pre>

<p>This Lead type matches the range of the Follow type, but with <code>a</code> and <code>b</code> swapped.  We can therefore type our bot friend as <code>a `Follow` b</code> and its partner as <code>b `Lead` a</code>, where</p>

<pre><code>type a `Follow` b =  a -&gt; Lead a b
type a `Lead`   b = (b, Follow a b)
</code></pre>

<p>This formulation makes it clear that the bot and the partner are simply different phases of the same kind of process (though with swapped type parameters).  While the bot is <code>a `Follow` b</code>, the partner is <code>b `Lead` a</code>; and while the bot is <code>a `Lead` b</code>, the partner is <code>b `Follow` a</code>.</p>

<p>Haskell won&#8217;t accept these mutually recursive types without at least one <code>newtype</code> or <code>data</code> wrapper.  We&#8217;ll use two.</p>

<pre><code>newtype a `Follow` b = Follow (a -&gt; Lead a b)
newtype a `Lead`   b =   Lead (b, Follow a b)
</code></pre>

<p><em>Aside:</em> I studied partner dancing pretty intensively a few years ago, during my mid-life sabbatical.  One of my later teachers rocked my conception of dancing when he said that the roles of &#8220;lead&#8221; and &#8220;follow&#8221; are not rigid, but alternate fluidly between the parters.  For instance the man (typically) initiates a movement (leads), which the woman (typically) responds to (follows).  The roles then smoothly reverse: the man then follows her as she leads him through completion of the movement, when the roles reverse again.</p>

<h2>Class instances</h2>

<p>Partially applied, both of these types are functors and applicative functors.</p>

<pre><code>instance Functor (Follow a) where
  fmap f (Follow h) = Follow (fmap f . h)

instance Applicative (Follow a) where
  pure b = Follow (const (pure b))
  Follow h &lt;*&gt; Follow k = Follow $  a -&gt; h a &lt;*&gt; k a

instance Functor (Lead a) where
  fmap f (Lead (b, g)) = Lead (f b, fmap f g)

instance Applicative (Lead a) where
  pure b = Lead (b, pure b)
  Lead (f,pf) &lt;*&gt; Lead (a,pa) = Lead (f a, pf &lt;*&gt; pa)
</code></pre>

<p>Since I&#8217;ve been playing with <code>Functor</code> and <code>Applicative</code> and type compositions a lot lately, some patterns in this code jump out at me.  It&#8217;s almost possible to get these four instances automatically, from very simple reformulations of <code>Follow</code> and <code>Lead</code>.  I&#8217;ll address those reformulations in another post.</p>

<p>An <code>Arrow</code> instance for <code>Follow</code> can be <a href="http://darcs.haskell.org/packages/bot/doc/html/src/Data-Bot-LeadFollow.html">adapted easily</a> from the <code>Arrow</code> instance for <code>Automaton</code>.  I don&#8217;t think it&#8217;s possible to define an <code>Arrow</code> instance for <code>Lead</code>, however.  Is it an instance of some other generic notion?</p>

<p>The type parameter order for <code>Follow</code> and <code>Lead</code> is always received before generated.  That order fits well with the type classes <code>Functor</code>, <code>Applicative</code>, and <code>Arrow</code>, while the reversed parameter order would mesh with contra-variant functors.  However, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Arrow.html" title="Library documentation: `Control.Arrow`">Control.Arrow</a> provides its own contravariant map (and related goodies):</p>

<pre><code>-- | Precomposition with a pure function.
(^&gt;&gt;) :: Arrow (~&gt;) =&gt; (b -&gt; c) -&gt; c ~&gt; d -&gt; b ~&gt; d
f ^&gt;&gt; a = arr f &gt;&gt;&gt; a
</code></pre>

<p>By the way, I prefer infix operators over the traditional form (e.g., <code>c ~&gt; d</code> vs <code>a c d</code>).  Keep in mind that &#8220;<code>-&gt;</code>&#8221; binds less strongly than other infix operators.</p>

<h2>Events and varying values</h2>

<p>One of the puzzles I&#8217;ve had about arrow-based reactivity is how to distinguish between events and reactive values.  The lead/follow dance provides an answer.  Here are the definitions, from <a href="http://conal.net/blog/posts/reactive-values-from-the-future/" title="Blog post: &quot;Reactive values from the future&quot;">Reactive values from the future</a>.</p>

<pre><code>newtype Event b = Future (Reactive b)

data Reactive b = Stepper b (Event b)
</code></pre>

<p>An event starts out in waiting mode&#8211;a sort of <em>pregnant</em> phase&#8211;until it gives birth to a reactive value.  A reactive value initially has a value and then acts like an event.  These two definitions are very like our <code>Follow</code> and <code>Lead</code>.  Where <code>Event</code> and <code>Reactive</code> use futures, the arrow-based formulations have explicit inputs (of type <code>a</code>).</p>

<p>Now that I have this follow/lead perspective, I regret my choice of the name &#8220;<code>Reactive</code>&#8221; for varying values.  Now I see that events are initially <em>reactive</em> (receptive), while varying values are initially <em>active</em> (generative).</p>

<h2>Getting chatty</h2>

<p>I&#8217;ve found it useful to allow any number of outputs in reaction to a single input.  In particular, filtering eliminates outputs, and <code>mappend</code> can combine outputs.  This flexibility motivated <a href="http://conal.net/blog/posts/functional-reactive-chatter-bots/" title="Blog post: &quot;Functional reactive chatter-bots&quot;">chatter-bots</a>.  The implementation is simple: use a list-valued output type, rewrapping as another abstraction.</p>

<pre><code>newtype a :&gt;- b = Leads   (Lead   a [b])
newtype a :-&gt; b = Follows (Follow a [b])
</code></pre>

<p>These types are also functors and applicative functors (when partially applied).  The instances are boilerplate for any composition of applicative functors.  The <code>Arrow</code> instance is a straightforward adaption from the <code>ChatterBot</code> instance given in <a href="http://conal.net/blog/posts/functional-reactive-chatter-bots/" title="Blog post: &quot;Functional reactive chatter-bots&quot;">Functional reactive chatter-bots</a>.</p>

<p>The <code>Lead</code> and <code>Follow</code> types are very similar to <a href="http://www.md.chalmers.se/Cs/Research/Functional/Fudgets/" title="Fudgets home page">Fudgets</a>-style stream processors, which provide output flexibility in a different way.  I will compare these two approaches in an upcoming post.</p>

<h2>Examples</h2>

<p>The examples from <a href="http://conal.net/blog/posts/accumulation-for-functional-reactive-chatter-bots/" title="Blog post: &quot;Accumulation for functional reactive chatter-bots&quot;">Accumulation for functional reactive chatter-bots</a> all work in the lead/follow setting, with changes to the function names.  Those examples were follows, but are more useful as leads, which we can now do as well, thanks to lead versions of the accumulating combinators.</p>

<p>As another example, let&#8217;s maintain the product of two independently-changing numbers.  In <a href="http://haskell.org/haskellwiki/Reactive" title="Wiki page for the Reactive library">Reactive</a>, we&#8217;d take two reactive (varying) values and return one:</p>

<pre><code>Reactive Int -&gt; Reactive Int -&gt; Reactive Int
</code></pre>

<p>We&#8217;ll have to re-arrange this interface to fit into the <code>Arrow</code>-style interface.  <a href="http://conal.net/blog/posts/reactive-values-from-the-future/" title="Blog post: &quot;Reactive values from the future&quot;">As described earlier</a>, a reactive value is simply a value and an event (analogous to a lead and a follow).  A bit of currying, argument flipping, and uncurrying gives the type</p>

<pre><code>(Int,Int) -&gt; (Event Int, Event Int) -&gt; Reactive Int
</code></pre>

<p>Next use the Event/pairing isomorphism:</p>

<pre><code>(Int,Int) -&gt; Event (Either Int Int) -&gt; Reactive Int
</code></pre>

<p>which converts to a Lead:</p>

<pre><code>prod :: (Int,Int) -&gt; Either Int Int :&gt;- Int
</code></pre>

<p>As first step, let&#8217;s decode the <code>Either</code>-valued input into a pair-modifying function</p>

<pre><code>updPair :: Either c d -&gt; (c,d) -&gt; (c,d)
updPair (Left  c') (_,d) = (c',d)
updPair (Right d') (c,_) = (c,d')
</code></pre>

<p>Or, the functionally svelte</p>

<pre><code>updPair = (first.const) `either` (second.const)
</code></pre>

<p>Using <code>updPair</code>, we can convert the <code>Either</code>-encoded pair edits to editing functions, and then cumulatively apply those functions.  (The <code>accumF</code> function is like <a href="http://conal.net/blog/posts/accumulation-for-functional-reactive-chatter-bots/" title="Blog post: &quot;Accumulation for functional reactive chatter-bots&quot;"><code>accumC</code> on chatter-bots</a>.)</p>

<pre><code>editPairF :: (c,d) -&gt; Either c d :-&gt; (c,d)
editPairF cd = updPair ^&gt;&gt; accumF cd
</code></pre>

<p>We have all we need to make a Lead version of pair editing as well:</p>

<pre><code>editPairL :: (c,d) -&gt; Either c d :&gt;- (c,d)
editPairL cd = leads [cd] (editPairF cd)
</code></pre>

<p>Or, with some pointfree-<em>fu</em>,</p>

<pre><code>    editPairL = leads.pure &lt;*&gt; editPairF
</code></pre>

<p>where <code>leads</code> is a convenience function:</p>

<pre><code>leads :: [b] -&gt; a :-&gt; b -&gt; a :&gt;- b
leads bs (Follows fol) = Leads (Lead (bs,fol))
</code></pre>

<p>Our <code>prod</code> example is now just a simple application of these generally useful pair editors.</p>

<pre><code>prod = (fmap.fmap) (uncurry (*)) editPairL
</code></pre>

<p>The first <code>fmap</code> is for <code>(-&gt;) (Int,Int)</code>, and the second is for <code>(:&gt;-) (Either Int Int)</code>.</p>
<p><a href="http://conal.net/blog/?flattrss_redirect&amp;id=17&amp;md5=4ba1b4145cb3870813e23b2184945b41"><img src="http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png" srcset="http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png, http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white@2x.png 2xhttp://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png, http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white@3x.png 3x" alt="Flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/functional-reactive-partner-dancing/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=conal&amp;popout=1&amp;url=http%3A%2F%2Fconal.net%2Fblog%2Fposts%2Ffunctional-reactive-partner-dancing&amp;language=en_GB&amp;category=text&amp;title=Functional+reactive+partner+dancing&amp;description=This+note+continues+an+exploration+of+arrow-friendly+formulations+of+functional+reactive+programming.+I+refine+the+previous+representations+into+an+interactive+dance+with+dynamically+interchanging+roles+of+follow+and+lead.+These...&amp;tags=applicative+functor%2Carrow%2Cbot%2Cdance%2CFRP%2Cfunctional+reactive+programming%2Cfunctor%2Clead%2Ffollow%2Cmutant%2Cblog" type="text/html" />
	</item>
		<item>
		<title>Functional reactive chatter-bots</title>
		<link>http://conal.net/blog/posts/functional-reactive-chatter-bots</link>
		<comments>http://conal.net/blog/posts/functional-reactive-chatter-bots#comments</comments>
		<pubDate>Wed, 06 Feb 2008 06:22:26 +0000</pubDate>
		<dc:creator><![CDATA[Conal]]></dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[applicative functor]]></category>
		<category><![CDATA[arrow]]></category>
		<category><![CDATA[bot]]></category>
		<category><![CDATA[chatter-bot]]></category>
		<category><![CDATA[FRP]]></category>
		<category><![CDATA[functional reactive programming]]></category>
		<category><![CDATA[functor]]></category>
		<category><![CDATA[monoid]]></category>
		<category><![CDATA[mutant]]></category>

		<guid isPermaLink="false">http://conal.net/blog/posts/invasion-of-the-composable-mutant-bots/</guid>
		<description><![CDATA[In a few recent posts, I&#8217;ve been writing about a new basis for functional reactive programming (FRP), embodied in the Reactive library. In those posts, events and reactive values are (first class) values. A reactive system able to produce outputs from inputs might have type Event a -&#62; Event b or perhaps Reactive a -&#62; [&#8230;]]]></description>
				<content:encoded><![CDATA[<!-- 

Title: Functional reactive chatter-bots

Tags: functional reactive programming, FRP, bot, arrows, monoids, functors, applicative functors, mutant, chatter-bot

URL: http://conal.net/blog/posts/functional-reactive-chatter-bots/

-->

<!-- references -->

<!-- teaser -->

<p>In a <a href="http://conal.net/blog/posts/reactive-values-from-the-future/" title="Blog post: &quot;Reactive values from the future&quot;">few</a> <a href="http://conal.net/blog/posts/reactive-normal-form/" title="Blog post: &quot;Reactive normal form&quot;">recent</a> <a href="http://conal.net/blog/posts/blending-continuity-into-reactive-values" title="Blog post: &quot;Blending continuity into reactive values&quot;">posts</a>, I&#8217;ve been writing about a new basis for functional reactive programming (FRP), embodied in the <a href="http://haskell.org/haskellwiki/Reactive" title="Wiki page for the Reactive library">Reactive</a> library.  In those posts, events and reactive values are (first class) values.  A reactive system able to produce outputs from inputs might have type <code>Event a -&gt; Event b</code> or perhaps <code>Reactive a -&gt; Reactive b</code>.</p>

<p>Although I&#8217;m mostly happy with the simplicity and expressiveness of this new formulation, I&#8217;ve also been thinking about arrow-style formulations, as in <a href="http://www.haskell.org/yale/papers/haskellworkshop01/index.html" title="Paper: &quot;Genuinely Functional User Interfaces&quot;">Fruit</a> and <a href="http://www.haskell.org/yampa" title="Project web page: &quot;Yampa: Functional Reactive Programming with Arrows&quot;">Yampa</a>.  Those systems expose <em>signal functions</em> in the programming interface, but relegate events and time-varying values (called &#8220;behaviors&#8221; in Fran and &#8220;signals&#8221; in Fruit and Yampa) to the semantics of signal functions.</p>

<p>If you&#8217;re not familiar with arrows in Haskell, you can find some getting-started information at the <a href="http://haskell.org/arrows" title="Arrows: A General Interface to Computation">arrows page</a>.</p>

<p>This post explores and presents a few arrow-friendly formulations of reactive systems.</p>

<p><strong>Edits</strong>:</p>

<ul>
<li>2008-02-06: Cleaned up the prose a bit.</li>
<li>2008-02-09: Simplified chatter-bot filtering.</li>
<li>2008-02-09: Renamed for easier topic recognition (was &#8220;Invasion of the composable Mutant-Bots&#8221;).</li>
<li>2008-02-10: Replaced <code>comps</code> by the simpler <code>concatMB</code> for sequential chatter-bot composition.</li>
</ul>

<!-- without a comment or something here, the last item above becomes a paragraph -->

<p><span id="more-14"></span></p>

<h2>Stream-bots</h2>

<p>Let&#8217;s look at some possibilities for formulating reactive systems.  The simplest formulation we might try is a function that maps an input stream to output stream.  Fortunately, Ross Paterson&#8217;s <a href="http://hackage.haskell.org/cgi-bin/hackage-scripts/package/arrows"><code>arrows</code> package</a> comes with an arrow transformer that <a href="http://hackage.haskell.org/packages/archive/arrows/0.3/doc/html/Control-Arrow-Transformer-Stream.html">adds stream inputs and outputs</a> to any arrow.  The instance definitions are very like <code>MapTrans</code> in <a href="http://www.soi.city.ac.uk/~ross/papers/fop.html" title="Paper: &quot;Arrows and Computation&quot;">Arrows and computation</a>.</p>

<pre><code>newtype StreamArrow (~&gt;) b c = Str (Stream b ~&gt; Stream c)

instance Arrow (~&gt;) =&gt; Arrow (StreamArrow (~&gt;)) where ...
</code></pre>

<p>In our case, the function arrow suffices:</p>

<pre><code>type StreamBot = StreamArrow (-&gt;)
</code></pre>

<p>Let&#8217;s assume for now that every input triggers exactly one output.  In a while, we&#8217;ll see that this assumption is easily relaxed, so there&#8217;s really no loss of generality.</p>

<h2>Other classes</h2>

<p>Although, the main attraction is the <code>Arrow</code> interface, Let&#8217;s look at some other classes as well.</p>

<h3>Functor and Applicative</h3>

<p><code>Functor</code> and <code>Applicative</code> instances for <code>StreamBot i</code> are immediate because <code>StreamBot</code> is an arrow.<sup id="fnref:arrow-based AF"><a href="#fn:arrow-based AF" rel="footnote">1</a></sup>  Therefore, for stream-bots,</p>

<pre><code>fmap :: (b -&gt; c) -&gt; StreamBot a b -&gt; StreamBot a c

pure  :: o -&gt; StreamBot i o
(&lt;*&gt;) :: StreamBot i (a -&gt; b) -&gt; StreamBot i a -&gt; StreamBot i b
</code></pre>

<p>These interfaces may sometimes be convenient in place of the <code>Arrow</code> interface.</p>

<p>What semantics do we get from the <code>Functor</code> and <code>Applicative</code> instances?</p>

<ul>
<li>In <code>fmap f bot</code>, <code>f</code> gets applied to each output of <code>bot</code></li>
<li>In <code>pure x</code>, each input triggers an <code>x</code> out.</li>
<li>In <code>fbot &lt;*&gt; xbot</code>, the same input stream is passed to each of <code>fbot</code> and <code>xbot</code>.  The functions coming out of <code>fbot</code> are applied to the corresponding arguments coming out of <code>xbot</code>.</li>
</ul>

<p><em>Note</em>: the semantics of <code>(&lt;*&gt;)</code> is very different from <code>(&lt;*&gt;)</code> on events in the <a href="http://haskell.org/haskellwiki/Reactive" title="Wiki page for the Reactive library">Reactive</a> library, as described in <a href="http://conal.net/blog/posts/reactive-values-from-the-future/" title="Blog post: &quot;Reactive values from the future&quot;">Reactive values from the future</a>.  Events work like lists, while bots work like <a href="http://www.cs.nott.ac.uk/~wss/repos/Stream/dist/doc/html/" title="Library docs: the Stream package">streams</a>.</p>

<h3>Monad</h3>

<p>I don&#8217;t know if there&#8217;s a useful or practical <code>Monad</code> instance for <code>StreamBot i</code> that is consistent with the <code>Applicative</code> instance (i.e., with <code>ap == (&lt;*&gt;)</code>).  I think each new bot to come out of <code>(&gt;&gt;=)</code> or <code>join</code> would have to be fed the same, full input stream, which would lead to a tremendous time-space leaks.</p>

<h3>Monoid</h3>

<p>Applicative functors (AFs) give rise to monoids through lifting.  A general declaration would be</p>

<pre><code>instance (Applicative f, Monoid o) =&gt; Monoid (f o) where
    mempty  = pure   mempty
    mappend = liftA2 mappend
</code></pre>

<p>Such an instance would overlap tremendously, but you can use it as a template.  For example (using <code>f = StreamArrow (~&gt;) i</code>),</p>

<pre><code>instance Monoid o =&gt; Monoid (StreamArrow (~&gt;) i o) where
    mempty  = pure   mempty
    mappend = liftA2 mappend
</code></pre>

<p>which applies to stream-bots as a special case.</p>

<p>So, <code>mappend</code> runs two bots in parallel, giving them the same inputs and combining each pair of outputs with <code>mappend</code> (on output values).  Of course, it only works when the output type in a monoid.</p>

<h2>Mutant-bots</h2>

<p>So far we&#8217;ve assumed that every input triggers exactly one output.  This assumption is critical in ensuring that <code>(&lt;*&gt;)</code> combines functions and arguments resulting from the same input.  The same requirement arises with <code>(***)</code> and even <code>first</code> in the <code>Arrow</code> instance.</p>

<p>Unfortunately, the stream-based representation (<code>Stream a -&gt; Stream b</code>) does not statically enforce the one-input-one-output property, i.e., it can represent bots that ignore some inputs and go <a href="http://en.wikipedia.org/wiki/Chatty_Cathy">Chatty-Cathy</a> over others.</p>

<p>We could maintain a feverish vigilance watching for rogue StreamBots, perhaps post guards working in shifts around the clock.  But fatigue sets in, and we could never be really confident.  Rather than losing sleep, let&#8217;s look for a representation that guarantees well-behaved bots.</p>

<p>What representation could we use instead?  We want one output per input, so let&#8217;s make our bot be a function from a single value, producing a single value.  After that input and output, we&#8217;d like another opportunity for an input, which would lead to another output and another opportunity for input, and so on:</p>

<pre><code>a -&gt; (b, a -&gt; (b, a -&gt; (b, ...)))
</code></pre>

<p>or, in recursive form:</p>

<pre><code>newtype MutantBot a b = Mutant (a -&gt; (b, MutantBot a b))
</code></pre>

<p>As this type definition shows, an input leads a possible bot mutation, as well as an output.</p>

<p>This bot formulation corresponds to a <a href="http://en.wikipedia.org/wiki/Mealy_machine">Mealy machine</a>, a classic automaton style for string transducers.</p>

<p>Ross&#8217;s <code>arrows</code> package already contains our mutant-bots, again in generalized to an arrow transformer:</p>

<pre><code>newtype Automaton (~&gt;) a b =
    Automaton (a ~&gt; (b, Automaton (~&gt;) a b))

instance Arrow (~&gt;) =&gt; Arrow (Automaton (~&gt;)) where ...
</code></pre>

<p>Because <code>Automaton</code> is a stream transformer, the <code>Functor</code>, <code>Applicative</code>, and <code>Monoid</code> instances mentioned above for <code>StreamArrow</code> all apply to <code>Automaton</code> as well.</p>

<p>So all that&#8217;s left for us is specializing:</p>

<pre><code>type MutantBot = Automaton (-&gt;)
</code></pre>

<h2>Choosy bots</h2>

<p>Now that I&#8217;ve praised mutant-bots for reliably producing a single output per input, I want to change the rules and drop that restriction.  Let&#8217;s give our bots freedom to choose whether or not to respond to an input.  Then we can formulate things like filtering (as in <a href="http://www.cse.unsw.edu.au/~dons/papers/stream-fusion.pdf" title="Paper: &quot;Stream fusion: from lists to streams to nothing at all&quot;">stream fusion</a>).  For instance, a bot might respond only to arrow keys.</p>

<p>Since we just dissed stream-bots for allowing this very freedom, we&#8217;ll want to proceed carefully.  The stream-bots run all of the outputs together, but our choosy-bots will produce one <em>optional</em> output per input and then mutate.  Instead of manufacturing a whole new bot line, we&#8217;ll ask the mutant-bots to simulate choosy-bots.  Rather than using <code>Maybe</code> directly, we&#8217;ll use <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t%3AFirst"><code>First</code></a>, which is a wrapper around <code>Maybe</code>:</p>

<pre><code>newtype ChoosyBot i o = Choosy (MutantBot i (First o))

newtype First a = First (Maybe a)  -- (in Data.Monoid)
</code></pre>

<h2>Cooperation and disagreements</h2>

<p>I mentioned above that <code>MutantBot i</code> is a monoid, in which <code>mappend</code> feeds inputs to two bots and merges their outputs with <code>mappend</code> (on the output type).  We&#8217;re in luck (or forethought)!  Choosy-bots use <code>First o</code> as output, which is a monoid for <em>all</em> <code>o</code> types.  Thus we can derive the <code>Monoid</code> implementation automatically, simply by adding &#8220;<code>deriving Monoid</code>&#8221; to the <code>ChoosyBot</code> definition.</p>

<p>In this derived instance, <code>mempty</code> stays silent, no matter what input, while <code>botA `mappend` botB</code> reacts according to whichever of <code>botA</code> or <code>botB</code> has a response.  In case both respond, <code>mappend</code> favors the  first bot.  To favor <code>botB</code> instead, we could have used <code>Last</code> in place of <code>First</code> in defining <code>ChoosyBot</code>.</p>

<h2>Chatter-bots</h2>

<p>When merged choosy-bots react to the same input, one response gets lost.  The representation itelf insists on picking only one response.  Instead of choosing, we can combine responses into a list.  The <code>Monoid</code> instance on lists does exactly the combination we want and can be lifted directly to chatter-bots.</p>

<pre><code>newtype ChatterBot i o = Chatter (MutantBot i [o]) deriving Monoid
</code></pre>

<p>We still have to show that <code>ChatterBot</code> is an arrow.</p>

<pre><code>instance Arrow ChatterBot where ...
</code></pre>

<p>To make an <code>i -&gt; o</code> function into a chatter-bot, just wrap up the outputs as singleton lists (with <code>pure</code> on lists):</p>

<pre><code>  arr h = Chatter (arr (pure . h))
</code></pre>

<p>We can build <code>first</code> out of the representation mutant-bot&#8217;s <code>first</code>, which makes a <code>MutantBot (a,c) ([bs],c)</code>.  Just share the <code>c</code> with each <code>b</code> in <code>bs</code>.</p>

<pre><code>  first (Chatter f) = Chatter $
    first f &gt;&gt;&gt; arr ( (bs,c) -&gt; [(b,c) | b &lt;- bs])
</code></pre>

<p>The key for sequential composition is an operation that feeds a list of inputs to a mutant-bot and collects the outputs and the final mutant.</p>

<pre><code>steps :: ([i], MutantBot i o) -&gt; ([o], MutantBot i o)
steps (is,bot) =
  first reverse $ foldl step ([], bot) is
 where
   step (os, Automaton f) i = first (:os) (f i)
</code></pre>

<p>With this utility, we can define a way to bundle up several multi-responses into one.</p>

<pre><code>concatMB :: MutantBot b [c] -&gt; MutantBot [b] [c]
concatMB bot = Automaton $  bs -&gt;
  (concat *** concatMB) (steps (bs,bot))
</code></pre>

<p>The <code>concatMB</code> function is just what we need for sequential chatter-bot composition:</p>

<pre><code>  Chatter ab &gt;&gt;&gt; Chatter bc = Chatter (ab &gt;&gt;&gt; concatMB bc)
</code></pre>

<p><em>Question</em>: can <code>comp</code> be generalized beyond lists?  If so, maybe we could unify and generalize choosy- and chatter-bots.</p>

<p>I like these chatter-bots so much that I&#8217;m giving them a prettier name:</p>

<pre><code>type (:-&gt;) = ChatterBot
</code></pre>

<h2>Filtering</h2>

<p>Chatter-bots can filter out values to which they don&#8217;t want to respond.  One simple means is analogous to <code>filter</code> on lists, taking a predicate saying which elements to keep:</p>

<pre><code>filterC :: (a -&gt; Bool) -&gt; a :-&gt; a
</code></pre>

<p>Another filtering tool consumes <code>Maybe</code> values:</p>

<pre><code>justC :: Maybe a :-&gt; a
</code></pre>

<p>Each <code>Nothing</code> gets dropped, and the <code>Just</code> constructors are stripped off what&#8217;s left.  The implementation is very simple.  The underlying mutant-bot converts <code>Nothing</code> with <code>[]</code> and <code>Just a</code> with <code>[a]</code>.  Luckily, there&#8217;s a standard function for that conversion.</p>

<pre><code>justC = Chatter (arr maybeToList)
</code></pre>

<p>It&#8217;s then easy to define <code>filterC</code> in terms of <code>justC</code>.</p>

<pre><code>filterC p = arr f &gt;&gt;&gt; justC
 where
   f a | p a       = Just a
       | otherwise = Nothing
</code></pre>

<p>One could also define <code>justC</code> in terms of <code>filterC</code>.</p>

<p>These two functions correspond to <code>filterMP</code> and <code>joinMaybes</code> discussed in &#8220;<a href="http://conal.net/blog/posts/a-handy-generalized-filter/" title="Blog post: &quot;A handy generalized filter&quot;">A handy generalized filter</a>&#8220;.</p>

<h2>Comparing arrow and non-arrow approaches</h2>

<p>Philosophically, I like that the arrow approach formalizes not only the output half of a behavior but
also the input (sensory) half.  I&#8217;ve long believed this formalization offers to solve the
spatial/temporal modularity problems of the original <a href="http://conal.net/Fran" title="Fran -- functional reactive animation">Fran</a> (inherited from <a href="http://conal.net/tbag" title="Project web page: &quot;TBAG: Time, Behavior, and Geometry&quot;">TBAG</a>).  (I
experimented with these issues in Fran but didn&#8217;t write it up, and I don&#8217;t think they&#8217;ve been addressed meanwhile.  Subject for another post.)  It also has <a href="http://www.cs.yale.edu/~hl293/download/leak.pdf" title="Paper: &quot;Plugging a Space Leak with an Arrow&quot;">implementation benefits</a>.</p>

<p>When using the arrow style, I miss flexibility and compositionity of types.  For instance, in <a href="http://haskell.org/haskellwiki/Reactive" title="Wiki page for the Reactive library">Reactive</a>, I can use <code>Reactive a -&gt; Reactive b -&gt; Reactive c</code> for a reactive system with two input sources.  As far as I know, arrows force me to encode every interface into a transformation of a single input source to a single output source.  In this case, I can use the (un)currying isomorphism and then the isomorphism of <code>(Reactive a, Reactive b)</code> with <code>Reactive (a,b)</code>.  For events instead of reactive values, that latter isomorphism does not hold.  Instead, <code>(Event a, Event b)</code> is isomorphic to <code>Event (Either a b)</code>.  (Magnus Carlsson noted the mismatch between arrows and fudgets, remarking that <a href="http://www.cse.ogi.edu/~magnus/ProdArrows" title="Paper: &quot;ProdArrows -- Arrows for Fudgets&quot;">&#8220;We need arrows that use sums as products&#8221;</a>.)</p>

<p>I also miss the flexibility to choose between events and reactive values.  Though similar, they have some very useful differences in their instances of <code>Applicative</code> and <code>Monad</code>.  For instance, for <code>Event</code>, <code>(&lt;*&gt;)</code> combines all pairs of occurrences (like the list instance), while for <code>Reactive</code>, <code>(&lt;*&gt;)</code> samples the function and argument for the same time (like the function instance).<!--  Also, the event monoid is very useful (temporal merging of occurrence streams), while the only monoid I can think of for reactive values is the lifted one (operating pointwise in time on an underlying monoid).--></p>

<p>The bots described above mix some semantics from events and some from reactive values.  The synchronous <code>Applicative</code> corresponds to reactive values, while the monoid is like that of <code>Event</code>.</p>

<p>One thing I like a lot about the implementations in this post, compared with Reactive, is that they do not need any concurrency, and so it&#8217;s easy to achieve deterministic semantics.  I don&#8217;t quite know how to do that for Reactive, as mentioned in &#8220;<a href="http://conal.net/blog/posts/future-values-via-multi-threading/" title="Blog post: &quot;Future values via multi-threading&quot;">Future values via multi-threading</a>.&#8221;</p>

<p>Finally, I wonder how efficient these bots are at <em>not</em> reacting to inputs.  In <a href="http://haskell.org/haskellwiki/Reactive" title="Wiki page for the Reactive library">Reactive</a>, if an event occurrence gets filtered out, propagation stops.  Chatter-bots continue to propagate empty values lists and bot non-mutations.</p>

<div class="footnotes">
<hr />
<ol>

<li id="fn:arrow-based AF">
<p>A template for arrow-based functors and applicative functors:</p>

<pre><code>-- Standard Functor &amp; Applicative instances for arrows.
instance Arrow (~&gt;) =&gt; Functor ((~&gt;) i) where fmap = (^&lt;&lt;)

instance Arrow (~&gt;) =&gt; Applicative ((~&gt;) i) where
    pure x = arr (const x)
    fbot &lt;*&gt; xbot = fbot &amp;&amp;&amp; xbot &gt;&gt;&gt; arr (uncurry ($))
</code></pre>

<p>The <code>WrappedArrow</code> type wrapper uses essentially these instances.&#160;<a href="#fnref:arrow-based AF" rev="footnote">&#8617;</a></p>
</li>

</ol>
</div>
<p><a href="http://conal.net/blog/?flattrss_redirect&amp;id=14&amp;md5=767795d177c0a08e776ad37e3262bbb6"><img src="http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png" srcset="http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png, http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white@2x.png 2xhttp://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png, http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white@3x.png 3x" alt="Flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/functional-reactive-chatter-bots/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=conal&amp;popout=1&amp;url=http%3A%2F%2Fconal.net%2Fblog%2Fposts%2Ffunctional-reactive-chatter-bots&amp;language=en_GB&amp;category=text&amp;title=Functional+reactive+chatter-bots&amp;description=In+a+few+recent+posts%2C+I%26%238217%3Bve+been+writing+about+a+new+basis+for+functional+reactive+programming+%28FRP%29%2C+embodied+in+the+Reactive+library.+In+those+posts%2C+events+and+reactive+values+are...&amp;tags=applicative+functor%2Carrow%2Cbot%2Cchatter-bot%2CFRP%2Cfunctional+reactive+programming%2Cfunctor%2Cmonoid%2Cmutant%2Cblog" type="text/html" />
	</item>
	</channel>
</rss>
