<?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; chatter-bot</title>
	<atom:link href="http://conal.net/blog/tag/chatter-bot/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>Accumulation for functional reactive chatter-bots</title>
		<link>http://conal.net/blog/posts/accumulation-for-functional-reactive-chatter-bots</link>
		<comments>http://conal.net/blog/posts/accumulation-for-functional-reactive-chatter-bots#comments</comments>
		<pubDate>Sun, 10 Feb 2008 05:47:03 +0000</pubDate>
		<dc:creator><![CDATA[Conal]]></dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[bot]]></category>
		<category><![CDATA[chatter-bot]]></category>
		<category><![CDATA[FRP]]></category>
		<category><![CDATA[functional reactive programming]]></category>

		<guid isPermaLink="false">http://conal.net/blog/posts/accumulation-for-functional-reactive-chatter-bots/</guid>
		<description><![CDATA[In Functional reactive chatter-bots, I described a few arrow-friendly formulations of functional reactive programming (FRP). This post shows how to define accumulation combinators and gives a few simple examples of their use. Accumulators on lists The various types of bots from the previous post all have in common that they map streams to streams. If [&#8230;]]]></description>
				<content:encoded><![CDATA[<!-- 

Title: Accumulation for functional reactive chatter-bots

Tags: functional reactive programming, FRP, bot, chatter-bot

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

-->

<!-- references -->

<!-- teaser -->

<p>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>, I described a few arrow-friendly formulations of functional reactive programming (FRP).  This post shows how to define accumulation combinators and gives a few simple examples of their use.</p>

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

<h2>Accumulators on lists</h2>

<p>The various types of bots from the <a href="http://conal.net/blog/posts/functional-reactive-chatter-bots/" title="Blog post: &quot;Functional reactive chatter-bots&quot;">previous post</a> all have in common that they map streams to streams.  If the bots were simply functions on lazy lists, we would probably use the <code>scanl</code> combinator:</p>

<pre><code>scanl :: (b -&gt; a -&gt; b) -&gt; b -&gt; [a] -&gt; [b]

scanl op b0 [a1, a2, ...] == [b0, b0 `op` a1, (b0 `op` a1) `op` a2, ...]
</code></pre>

<p>Our bots wait for input before producing output, so we&#8217;d want to drop the first element of the result (<code>b0</code>).  (In a future post, we&#8217;ll meet some more assertive bots.) If we didn&#8217;t already have <code>scanl</code>, we might implement this new behavior as follows:</p>

<pre><code>scanlTl :: (b -&gt; a -&gt; b) -&gt; b -&gt; [a] -&gt; [b]
scanlTl _ _ []     = []
scanlTl f b (a:as) = let b' = f b a in b' : scanlTl f b' as
</code></pre>

<p>I often use a variation that successively applies functions from a function stream.</p>

<pre><code>accum :: a -&gt; [a-&gt;a] -&gt; [a]
accum _ [] = []
accum a (f:fs) = a' : accum a' fs where a' = f a
</code></pre>

<p>or just</p>

<pre><code>accum = scanlTl (flip ($))
</code></pre>

<h2>Mutant-bots</h2>

<p>To see how to incorporate <code>scanl</code> into BotWorld, let&#8217;s start with the simpler mutant-bots.  The implementation directly follows <code>scanlTl</code>, except that we drop the empty case, since we assume our input streams to be infinite.</p>

<pre><code>scanlM :: (b -&gt; a -&gt; b) -&gt; b -&gt; MutantBot a b
scanlM f b = Automaton $  a -&gt; let b' = f b a in (b', scanlM f b')
</code></pre>

<p>We can then make a mutant-bot version of <code>accum</code>:</p>

<pre><code>accumM :: a -&gt; MutantBot (a-&gt;a) a
accumM = scanlM (flip ($))
</code></pre>

<h2>Chatter-bots</h2>

<p>A chatter-bot is represented as a (<code>newtype</code>-wrapped) mutant-bot whose output values are lists.  For accumulation, we&#8217;ll have singleton (<code>pure</code>) lists coming out.</p>

<pre><code>scanlC :: (b -&gt; a -&gt; b) -&gt; b -&gt; (a :~&gt; b)
scanlC f b = Chatter $ pure &lt;$&gt; scanlM f b

accumC :: a -&gt; ((a-&gt;a) :~&gt; a)
accumC = scanlC (flip ($))
</code></pre>

<h2>Examples</h2>

<p>Here are a few examples of <code>scanlC</code> and <code>accumC</code>.</p>

<p>Keep a running count of inputs:</p>

<pre><code>count :: a :-&gt; Int
count = scanlC ( b _ -&gt; b + 1) 0
</code></pre>

<p>Flip-flop between <code>False</code> and <code>True</code>:</p>

<pre><code>flipFlop :: a :-&gt; Bool
flipFlop = scanlC ( b _ -&gt; not b) False
</code></pre>

<p>Add up inputs:</p>

<pre><code>sum :: Num a =&gt; a :-&gt; a
sum = scanlC (+) 0
</code></pre>

<p>Count the odd inputs:</p>

<pre><code>coundOdd :: Integral a =&gt; a :-&gt; Int
coundOdd = filterC odd &gt;&gt;&gt; count
</code></pre>

<p>Increment/decrement a counter (possibly both or neither), depending on whether inputs satisfy each of two predicates.</p>

<pre><code>upDown :: forall a. (a -&gt; Bool) -&gt; (a -&gt; Bool) -&gt; a :-&gt; Int
upDown isUp isDown = (up `mappend` down) &gt;&gt;&gt; accumC 0
 where
   up, down :: a :-&gt; (Int -&gt; Int)
   up   = filterC isUp   &gt;&gt;&gt; replace (+ 1)
   down = filterC isDown &gt;&gt;&gt; replace (subtract 1)

-- Respond to each input with the same value
replace :: Arrow (~&gt;) =&gt; b -&gt; a ~&gt; b
replace b = arr (const b)
</code></pre>

<h2>How are we doing, and where are we going?</h2>

<p>I&#8217;m encouraged with how simply accumulation works out.  Most of the pieces of <a href="http://haskell.org/haskellwiki/Reactive" title="Wiki page for the Reactive library">Reactive</a> have chatter-bot counterparts now.  The implementation doesn&#8217;t require multi-threading (as Reactive uses), so it was easy to get purely deterministic semantics.</p>

<p>Still to come:</p>

<ul>
<li>Snapshot a varying value whenever an event occurs.</li>
<li>A clear notion of varying values (in progress).</li>
<li>GUI examples.</li>
<li>Source code release.</li>
<li>Work out how to use the arrow-styled interface with TV, which uses currying and pairing (in progress).</li>
</ul>
<p><a href="http://conal.net/blog/?flattrss_redirect&amp;id=16&amp;md5=b5d1252a6d18de74a5c55ed2223b82e5"><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/accumulation-for-functional-reactive-chatter-bots/feed</wfw:commentRss>
		<slash:comments>1</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%2Faccumulation-for-functional-reactive-chatter-bots&amp;language=en_GB&amp;category=text&amp;title=Accumulation+for+functional+reactive+chatter-bots&amp;description=In+Functional+reactive+chatter-bots%2C+I+described+a+few+arrow-friendly+formulations+of+functional+reactive+programming+%28FRP%29.+This+post+shows+how+to+define+accumulation+combinators+and+gives+a+few+simple+examples+of...&amp;tags=bot%2Cchatter-bot%2CFRP%2Cfunctional+reactive+programming%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>
