<?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; arrow</title>
	<atom:link href="http://conal.net/blog/tag/arrow/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>Thoughts on semantics for 3D graphics</title>
		<link>http://conal.net/blog/posts/thoughts-on-semantics-for-3d-graphics</link>
		<comments>http://conal.net/blog/posts/thoughts-on-semantics-for-3d-graphics#comments</comments>
		<pubDate>Mon, 23 Nov 2009 07:41:30 +0000</pubDate>
		<dc:creator><![CDATA[Conal]]></dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[3D]]></category>
		<category><![CDATA[arrow]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[geometry]]></category>
		<category><![CDATA[semantics]]></category>
		<category><![CDATA[type class morphism]]></category>

		<guid isPermaLink="false">http://conal.net/blog/?p=90</guid>
		<description><![CDATA[The central question for me in designing software is always What does it mean? With functional programming, this question is especially crisp. For each data type I define, I want to have a precise and simple mathematical model. (For instance, my model for behavior is function-of-time, and my model of images is function-of-2D-space.) Every operation [&#8230;]]]></description>
				<content:encoded><![CDATA[<!-- 

Title: Thoughts on semantics for 3D graphics

Tags: semantics, design, 3D, arrow, type class morphism, geometry

URL: http://conal.net/blog/posts/thoughts-on-semantics-for-3d-graphics/

-->

<!-- references -->

<!-- teaser -->

<p>The central question for me in designing software is always</p>

<blockquote>
  <p>What does it mean?</p>
</blockquote>

<p>With functional programming, this question is especially crisp.
For each data type I define, I want to have a precise and simple mathematical model.
(For instance, my model for behavior is function-of-time, and my model of images is function-of-2D-space.)
Every operation on the type is also given a meaning in terms of that semantic model.</p>

<p>This specification process, which is denotational semantics applied to data types, provides a basis for</p>

<ul>
<li>correctness of the implementation,</li>
<li>user documentation free of implementation detail,</li>
<li>generating and proving properties, which can then be used in automated testing, and</li>
<li>evaluating and comparing the elegance and expressive power of design decisions.</li>
</ul>

<p>For an example (2D images), some motivation of this process, and discussion, see Luke Palmer&#8217;s post <em><a href="http://lukepalmer.wordpress.com/2008/07/18/semantic-design/" title="Blog post by Luke Palmer">Semantic Design</a></em>.
See also my posts on the idea and use of <em><a href="http://conal.net/blog/tag/type-class-morphism/" title="Posts on type class morphisms">type class morphisms</a></em>, which provide additional structure to denotational design.</p>

<p>In spring of 2008, I started working on a functional 3D library, <a href="http://haskell.org/haskellwiki/FieldTrip" title="Library wiki page">FieldTrip</a>.
I&#8217;ve designed functional 3D libraries before as part of <a href="http://conal.net/tbag/" title="Project web page">TBAG</a>, <a href="http://conal.net/papers/ActiveVRML/" title="Tech report: &quot;A Brief Introduction to ActiveVRML&quot;">ActiveVRML</a>, and <a href="http://conal.net/Fran" title="Functional reactive animation">Fran</a>.
This time I wanted a semantics-based design, for all of the reasons given above.
As always, I want a model that is</p>

<ul>
<li>simple, </li>
<li>elegant, and </li>
<li>general.</li>
</ul>

<p>For 3D, I also want the model to be GPU-friendly, i.e., to execute well on (modern) GPUs and to give access to their abilities.</p>

<p>I hadn&#8217;t thought of or heard a model that I was happy with, and so I didn&#8217;t have the sort of firm ground I like to stand on in working on FieldTrip.
Last February, such a model occurred to me.
I&#8217;ve had this blog post mostly written since then.
Recently, I&#8217;ve been focused on functional 3D again for GPU-based rendering, and then Sean McDirmid <a href="http://mcdirmid.wordpress.com/2009/11/20/designing-a-gpu-oriented-geometry-abstraction-part-one/">posed a similar question</a>, which got me thinking again.</p>

<!--
**Edits**:

* 2008-02-09: just fiddling around
-->

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

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

<h3>Geometry</h3>

<p>3D graphics involves a variety of concepts.
Let&#8217;s start with 3D geometry, using a <em>surface</em> (rather than a <em>solid</em>) model.</p>

<p>Examples of 3D (surface) geometry include</p>

<ul>
<li>the boundary (surface) of a solid box, sphere, or torus,</li>
<li>a filled triangle, rectangle, or circle,</li>
<li>a collection of geometry , and</li>
<li>a spatial transformation of geometry.</li>
</ul>

<h4>First model: set of geometric primitives</h4>

<p>One model of geometry is a set of geometric primitives.
In this model, <code>union</code> means set union, and spatial transformation means transforming all of the 3D points in all of the primitives in the set.
Primitives contain infinitely (even uncountably) many points, so that&#8217;s a lot of transforming.
Fortunately, we&#8217;re talking about what (semantics), and not how (implementation).</p>

<p><em>What is a geometric primitive?</em></p>

<p>We could say it&#8217;s a triangle, specified by three coordinates.
After all, computer graphics reduces everything to sets of triangles.
Oops &#8212; we&#8217;re confusing semantics and implementation.
Tessellation <em>approximates</em> curved surfaces by sets of triangles but loses information in the process.
I want a story that includes this approximation process but keeps it clearly distinct from semantically ideal curved surfaces.
Then users can work with the ideal, simple semantics and rely on the implementation to perform intelligent, dynamic, view-dependent tessellation that adapts to available hardware resources.</p>

<p>Another model of geometric primitive is a function from 2D space to 3D space, i.e., the &#8220;parametric&#8221; representation of surfaces.
Along with the function, we&#8217;ll probably want some means of describing the subset of 2D over which the surface is defined, so as to trim our surfaces.
A simple formalization would be</p>

<pre><code>type Surf = R2 -&gt; Maybe R3
</code></pre>

<p>where</p>

<pre><code>type R  -- real numbers
type R2 = (R,R)
type R3 = (R,R,R)
</code></pre>

<p>For shading, we&#8217;ll also need normals, and possibly tangents &amp; bitangents,
We can get these features and more by including derivatives, either just first derivatives or all of them.
See my <a href="http://conal.net/blog/tag/derivative/" title="Posts on derivatives">posts on derivatives</a> and paper <em><a href="http://conal.net/papers/beautiful-differentiation/" title="Paper: Beautiful differentiation">Beautiful differentiation</a></em>.</p>

<p>In addition to position and derivatives, each point on a primitive also has material properties, which determines how light is reflected by and transmitted through the surface at the point.</p>

<pre><code>type Surf = R2 -&gt; Maybe (R2 :&gt; R3, Material)
</code></pre>

<p>where <code>a :&gt; b</code> contains all derivatives (including zeroth) at a point of a function of type <code>a-&gt;b</code>.
See <em><a href="http://conal.net/blog/posts/higher-dimensional-higher-order-derivatives-functionally/" title="blog post">Higher-dimensional, higher-order derivatives, functionally</a></em>.
We could perhaps also include derivatives of material properties:</p>

<pre><code>type Surf = R2 :~&gt; Maybe (R3, Material)
</code></pre>

<p>where <code>a :~&gt; b</code> is the type of infinitely differentiable functions.</p>

<h4>Combining geometry values</h4>

<p>The <code>union</code> function gives one way to combine two geometry values.
Another is morphing (interpolation) of positions and of material properties.
What can the semantics of morphing be?</p>

<p>Morphing betwen two <em>surfaces</em> is easier to define.
A surface is a function, so we can interpolate <em>point-wise</em>: given surfaces <code>r</code> and <code>s</code>, for each point <code>p</code> in parameter space, interpolate between (a) <code>r</code> at <code>p</code> and (b) <code>s</code> at <code>p</code>, which is what <code>liftA2</code> (on functions) would suggest.</p>

<p>This definition works <em>if</em> we have a way to interpolate between <code>Maybe</code> values.
If we use <code>liftA2</code> again, now on <code>Maybe</code> values, then the <code>Just</code>/<code>Nothing</code> (and <code>Nothing</code>/<code>Just</code>) cases will yield <code>Nothing</code>.
Is this semantics desirable?
As an example, consider a flat square surface with hole in the middle.
One square has a small hole, and the other has a big hole.
If the size of the hole corresponds to size of the portion of parameter space mapped to <code>Nothing</code>, then point-wise interpolation will always yield the larger hole, rather than interpolating between hole sizes.
On the other hand, the two surfaces with holes might be <code>Just</code> over exactly the same set of parameters, with the function determining how much the <code>Just</code> space gets stretched.</p>

<p>One way to characterize this awkwardness of morphing is that the two functions (surfaces) might have <em>different domains</em>.
This interpretation comes from seeing <code>a -&gt; Maybe b</code> as encoding a function from a <em>subset</em> of <code>a</code> (i.e., a <em>partial</em> function on <code>a</code>).</p>

<p>Even if we had a satisfactory way to combine surfaces (point-wise), how could we extend it to combining full geometry values, which can contain any number of surfaces?
One idea is to model geometry as an <em>structured</em> collection of surfaces, e.g., a list.
Then we could combine the collections element-wise.
Again, we&#8217;d have to deal with the possibility that the collections do not match up.</p>

<h3>Surface tuples</h3>

<p>Let&#8217;s briefly return to a simpler model of surfaces:</p>

<pre><code>type Surf = R2 -&gt; R3
</code></pre>

<p>We could represent a collection of such surfaces as a structured collection, e.g., a list:</p>

<pre><code>type Geometry = [Surf]
</code></pre>

<p>But then the type doesn&#8217;t capture the number of surfaces, leading to mismatches when combining geometry values point-wise.</p>

<p>Alternatively, we could make the number of surfaces explicit in the type, via tuples, possibly nested.
For instance, two surfaces would have type <code>(Surf,Surf)</code>.</p>

<p>Interpolation in this model becomes very simple.
A general interpolator works on vector spaces:</p>

<pre><code>lerp :: VectorSpace v =&gt; v -&gt; v -&gt; Scalar v -&gt; v
lerp a b t = a ^+^ t*^(b ^-^ a)
</code></pre>

<p>or on affine spaces:</p>

<pre><code>alerp :: (AffineSpace p, VectorSpace (Diff p)) =&gt;
         p -&gt; p -&gt; Scalar (Diff p) -&gt; p
alerp p p' s = p .+^ s*^(p' .-. p)
</code></pre>

<p>Both definitions are in the <a href="http://haskell.org/haskellwiki/vector-space" title="Library wiki page">vector-space</a> package.
That package also includes <code>VectorSpace</code> and <code>AffineSpace</code> instances for both functions and tuples.
These instances, together with instances for real values suffice to make (possibly nested) tuples of surfaces be vector spaces and affine spaces.</p>

<h3>From products to sums</h3>

<p>Function pairing admits some useful isomorphisms.
One replaces a product with a product:</p>

<!-- $$(a to b) times (a to c) cong a to (b times c)$$ -->

<pre><code>(a → b) × (a → c) ≅ a → (b × c)
</code></pre>

<p>Using this product/product isomorphism, we could replace tuples of surfaces with a single function from <em>R<sup>2</sup></em> to tuples of <em>R<sup>3</sup></em>.</p>

<p>There is also a handy isomorphism that relates products to sums, in the context of functions:</p>

<!-- $$(b to a) times (c to a) cong (b + c) to a$$ -->

<pre><code>(b → a) × (c → a) ≅ (b + c) → a
</code></pre>

<p>This second isomorphism lets us replace tuples of surfaces with a single &#8220;surface&#8221;, if we generalize the notion of surface to include domains more complex than <em>R<sup>2</sup></em>.</p>

<p>In fact, these two isomorphisms are uncurried forms of the general and useful Haskell functions <code>(&amp;&amp;&amp;)</code> and <code>(|||)</code>, defined on arrows:</p>

<pre><code>(&amp;&amp;&amp;) :: Arrow       (~&gt;) =&gt; (a ~&gt; b) -&gt; (a ~&gt; c) -&gt; (a ~&gt; (b,c))
(|||) :: ArrowChoice (~&gt;) =&gt; (a ~&gt; c) -&gt; (b ~&gt; c) -&gt; (Either a b ~&gt; c)
</code></pre>

<p>Restricted to the function arrow, <code>(|||) == either</code>.</p>

<p>The second isomorphism, <code>uncurry (|||)</code>, has another benefit.
Relaxing the domain type to allow sums opens the way to other domain variations as well.
For instance, we can have types for triangular domains, shapes with holes, and other flavors of bounded and unbounded parameter spaces.
All of these domains are two-dimensional, although they may result from several patches.</p>

<p>Our <code>Geometry</code> type now becomes parameterized:</p>

<pre><code>type Geometry a = a -&gt; (R3,Material)
</code></pre>

<p>The first isomorphism, <code>uncurry (&amp;&amp;&amp;)</code>, is also useful in a geometric setting.
Think of each component of the range type (here <code>R3</code> and <code>Material</code>) as a surface &#8220;attribute&#8221;.
Then <code>(&amp;&amp;&amp;)</code> merges two compatible geometries, including attributes from each.
Attributes could include position (and derivatives) and shading-related material, as well as non-visual properties like temperature, elasticity, stickiness, etc.</p>

<p>With this flexibility in mind, <code>Geometry</code> gets a second type parameter, which is the range type.
Now there&#8217;s nothing left of the <code>Geometry</code> type but general functions:</p>

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

<p>Recall that we&#8217;re looking for a <em>semantics</em> for 3D geometry.
The <em>type</em> for <code>Geometry</code> might be abstract, with <code>(-&gt;)</code> being its semantic model.
In that case, the model suggests that <code>Geometry</code> have all of the same type class instances that <code>(-&gt;)</code> (and its full or partial applications) has, including <code>Monoid</code>, <code>Functor</code>, <code>Applicative</code>, <code>Monad</code>, and <code>Arrow</code>.
The semantics of these instances would be given by the corresponding instances for <code>(-&gt;)</code>.
(See posts on <a href="http://conal.net/blog/tag/type-class-morphism/" title="Posts on type class morphisms">type class morphisms</a> and the paper <em><a href="http://conal.net/blog/posts/denotational-design-with-type-class-morphisms/" title="blog post">Denotational design with type class morphisms</a></em>.)</p>

<p>Or drop the notion of <code>Geometry</code> altogether and use functions directly.</p>

<h3>Domains</h3>

<p>I&#8217;m happy with the simplicity of geometry as functions.
Functions fit the flexibility of programmable GPUs, and they provide simple, powerful &amp; familiar notions of attribute merging (<code>(&amp;&amp;&amp;)</code>) and union (<code>(|||)</code>/<code>either</code>).</p>

<p>The main question I&#8217;m left with: what are the domains?</p>

<p>One simple domain is a one-dimensional interval, say [-1,1].</p>

<p>Two useful domain building blocks are sum and product.
I mentioned sum above, in connection with geometric union (<code>(|||)</code>/<code>either</code>)
Product combines domains into higher-dimensional domains.
For instance, the product of two 1D intervals is a 2D interval (axis-aligned filled rectangle), which is handy for some parametric surfaces.</p>

<p>What about other domains, e.g., triangular, or having one more holes?  Or multi-way branching surfaces?  Or unbounded?</p>

<p>One idea is to stitch together simple domains using sum.
We don&#8217;t have to build any particular spatial shapes or sizes, since the &#8220;geometry&#8221; functions themselves yield the shape and size.
For instance, a square region can be mapped to a triangular or even circular region.
An infinite domain can be stitched together from infinitely many finite domains.
Or it can be mapped to from a single finite domain.
For instance, the function <code>x -&gt; x / abs (1-x)</code> maps [-1,1] to [-∞,∞].</p>

<p>Alternatively, we could represent domains as typed predicates (characteristic functions).
For instance, the closed interval [-1,1] would be <code>x -&gt; abs x &lt;= 1</code>.
Replacing <code>abs</code> with <code>magnitude</code> (for <a href="http://hackage.haskell.org/packages/archive/vector-space/latest/doc/html/Data-VectorSpace.html#t%3AInnerSpace">inner product spaces</a>), generalizes this formulation to encompass [-1,1] (1D), a unit disk (2D), and a unit ball (3D).</p>

<p>I like the simple generality of the predicate approach, while I like how the pure type approach supports interpolation and other pointwise operations (via <code>liftA2</code> etc).</p>

<h3>Tessellation</h3>

<p>I&#8217;ve intentionally formulated the graphics semantics over continuous space, which makes it resolution-independent and easy to compose.
(This formulation is typical for 3D geometry and 2D vector graphics.
The benefits of continuity apply to generally <a href="http://conal.net/Pan/Gallery" title="Pan image gallery">imagery</a> and to <a href="http://conal.net/Fran/tutorial.htm" title="Animated tutorial: &quot;Composing Reactive Animations&quot;">animation/behavior</a>.)</p>

<p>Graphics hardware specializes in finite collections of triangles.
For rendering, curved surfaces have to be <em>tessellated</em>, i.e., approximated as collections of triangles.
Desirable choice of tessellation depends on characteristics of the surface and of the view, as well as scene complexity and available CPU and GPU resources.
Formulating geometry in its ideal curved form allows for automated analysis and choice of tessellation.
For instance, since triangles are linear, the error of a triangle relative to the surface it approximates depends on how <em>non-linear</em> the surface is over the subset of its domain corresponding to the triangle.
Using <a href="http://en.wikipedia.org/wiki/Talk:Interval_arithmetic" title="Wikipedia page on interval analysis/arithmetic">interval analysis</a> and <a href="http://conal.net/blog/tag/derivative/" title="Posts on derivatives">derivatives</a>, non-linearity can be measured as a size bound on the second derivative or a range of first derivative.
Error could also be analyzed in terms of the resulting image rather than the surface.</p>

<p>For a GPU-based implementation, one could tessellate dynamically, in a &#8220;geometry shader&#8221; or (I presume) in a more general framework like CUDA or OpenCL.</p>

<h3>Abstractness</h3>

<p>A denotational model is &#8220;fully abstract&#8221; when it equates observationally equivalent terms.
The parametric model of surfaces is not fully abstract in that reparameterizing a surface yields a different function that looks the same as a surface.
(Surface reparametrization alters the relationship between domain and range, while covering exactly the same surface, geometrically.)
Properties that are independent of particular parametrization are called &#8220;geometric&#8221;, which I think corresponds to full abstraction (considering those properties as semantic functions).</p>

<p>What might a fully abstract (geometric) model for geometry be?</p>
<p><a href="http://conal.net/blog/?flattrss_redirect&amp;id=90&amp;md5=3a9d3f59c6f8c7d6110dbfab2555bddf"><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/thoughts-on-semantics-for-3d-graphics/feed</wfw:commentRss>
		<slash:comments>18</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%2Fthoughts-on-semantics-for-3d-graphics&amp;language=en_GB&amp;category=text&amp;title=Thoughts+on+semantics+for+3D+graphics&amp;description=The+central+question+for+me+in+designing+software+is+always+What+does+it+mean%3F+With+functional+programming%2C+this+question+is+especially+crisp.+For+each+data+type+I+define%2C+I+want...&amp;tags=3D%2Carrow%2Cdesign%2Cgeometry%2Csemantics%2Ctype+class+morphism%2Cblog" type="text/html" />
	</item>
		<item>
		<title>Denotational design with type class morphisms</title>
		<link>http://conal.net/blog/posts/denotational-design-with-type-class-morphisms</link>
		<comments>http://conal.net/blog/posts/denotational-design-with-type-class-morphisms#comments</comments>
		<pubDate>Thu, 19 Feb 2009 02:34:08 +0000</pubDate>
		<dc:creator><![CDATA[Conal]]></dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[applicative functor]]></category>
		<category><![CDATA[arrow]]></category>
		<category><![CDATA[associated type]]></category>
		<category><![CDATA[functor]]></category>
		<category><![CDATA[monad]]></category>
		<category><![CDATA[monoid]]></category>
		<category><![CDATA[paper]]></category>
		<category><![CDATA[semantics]]></category>
		<category><![CDATA[trie]]></category>
		<category><![CDATA[type class morphism]]></category>

		<guid isPermaLink="false">http://conal.net/blog/?p=84</guid>
		<description><![CDATA[I&#8217;ve just finished a draft of a paper called Denotational design with type class morphisms, for submission to ICFP 2009. The paper is on a theme I&#8217;ve explored in several posts, which is semantics-based design, guided by type class morphisms. I&#8217;d love to get some readings and feedback. Pointers to related work would be particularly [&#8230;]]]></description>
				<content:encoded><![CDATA[<!-- 

Title: Denotational design with type class morphisms

Tags: paper, semantics, type class morphism, monoid, functor, applicative functor, monad, arrow, associated type, trie

URL: http://conal.net/blog/posts/denotational-design-with-type-class-morphisms/

-->

<!-- references -->

<!-- teaser -->

<p>I&#8217;ve just finished a draft of a paper called <em><a href="http://conal.net/papers/type-class-morphisms" title="paper">Denotational design with type class morphisms</a></em>, for submission to <a href="http://www.cs.nott.ac.uk/~gmh/icfp09.html" title="conference page">ICFP 2009</a>.
The paper is on a theme I&#8217;ve explored in <a href="http://conal.net/blog/tag/type-class-morphism/">several posts</a>, which is semantics-based design, guided by type class morphisms.</p>

<p>I&#8217;d love to get some readings and feedback.
Pointers to related work would be particularly appreciated, as well as what&#8217;s unclear and what could be cut.
It&#8217;s an entire page over the limit, so I&#8217;ll have to do some trimming before submitting.</p>

<p>The abstract:</p>

<blockquote>
  <p>Type classes provide a mechanism for varied implementations of standard
  interfaces. Many of these interfaces are founded in mathematical
  tradition and so have regularity not only of <em>types</em> but also of
  <em>properties</em> (laws) that must hold. Types and properties give strong
  guidance to the library implementor, while leaving freedom as well. Some
  of the remaining freedom is in <em>how</em> the implementation works, and some
  is in <em>what</em> it accomplishes.</p>
  
  <p>To give additional guidance to the <em>what</em>, without impinging on the
  <em>how</em>, this paper proposes a principle of <em>type class morphisms</em> (TCMs),
  which further refines the compositional style of denotational
  semantics. The TCM idea is simply that <em>the instance&#8217;s meaning is the
  meaning&#8217;s instance</em>. This principle determines the meaning of each type
  class instance, and hence defines correctness of implementation. In some
  cases, it also provides a systematic guide to implementation, and in
  some cases, valuable design feedback.</p>
  
  <p>The paper is illustrated with several examples of type, meanings, and
  morphisms.</p>
</blockquote>

<p>You can <a href="http://conal.net/papers/type-class-morphisms" title="paper">get the paper and see current errata here</a>.</p>

<p>The submission deadline is March 2, so comments before then are most helpful to me.</p>

<p>Enjoy, and thanks!</p>

<!--
**Edits**:

* 2009-02-09: just fiddling around
-->
<p><a href="http://conal.net/blog/?flattrss_redirect&amp;id=84&amp;md5=8ce3b83d01ccfad97ade1469b72d2a04"><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/denotational-design-with-type-class-morphisms/feed</wfw:commentRss>
		<slash:comments>8</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%2Fdenotational-design-with-type-class-morphisms&amp;language=en_GB&amp;category=text&amp;title=Denotational+design+with+type+class+morphisms&amp;description=I%26%238217%3Bve+just+finished+a+draft+of+a+paper+called+Denotational+design+with+type+class+morphisms%2C+for+submission+to+ICFP+2009.+The+paper+is+on+a+theme+I%26%238217%3Bve+explored+in+several...&amp;tags=applicative+functor%2Carrow%2Cassociated+type%2Cfunctor%2Cmonad%2Cmonoid%2Cpaper%2Csemantics%2Ctrie%2Ctype+class+morphism%2Cblog" type="text/html" />
	</item>
		<item>
		<title>Semantic editor combinators</title>
		<link>http://conal.net/blog/posts/semantic-editor-combinators</link>
		<comments>http://conal.net/blog/posts/semantic-editor-combinators#comments</comments>
		<pubDate>Tue, 25 Nov 2008 06:06:52 +0000</pubDate>
		<dc:creator><![CDATA[Conal]]></dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[applicative functor]]></category>
		<category><![CDATA[arrow]]></category>
		<category><![CDATA[combinator]]></category>
		<category><![CDATA[editor]]></category>
		<category><![CDATA[technique]]></category>
		<category><![CDATA[type composition]]></category>

		<guid isPermaLink="false">http://conal.net/blog/?p=64</guid>
		<description><![CDATA[While working on Eros, I encountered a function programming pattern I hadn&#8217;t known. I was struck by the simplicity and power of this pattern, and I wondered why I hadn&#8217;t run into it before. I call this idea &#8220;semantic editor combinators&#8221;, because it&#8217;s a composable way to create transformations on rich values. I&#8217;m writing this [&#8230;]]]></description>
				<content:encoded><![CDATA[<!-- 

Title: Semantic editor combinators

Tags: editor, combinator, arrow, applicative functor, technique, type composition

URL: http://conal.net/blog/posts/semantic-editor-combinators/

-->

<!-- references -->

<!-- teaser -->

<p>While working on <a href="http://haskell.org/haskellwiki/Eros" title="Wiki page: Eros -- tangible functional programming">Eros</a>, I encountered a function programming pattern I hadn&#8217;t known.
I was struck by the simplicity and power of this pattern, and I wondered why I hadn&#8217;t run into it before.
I call this idea &#8220;semantic editor combinators&#8221;, because it&#8217;s a composable way to create transformations on rich values.
I&#8217;m writing this post in order to share this simple idea, which is perhaps &#8220;almost obvious&#8221;, but not quite, due to two interfering habits:</p>

<ul>
<li>thinking of function composition as binary instead of unary, and</li>
<li>seeing the functions <code>first</code> and <code>second</code> as about arrows, and therefore esoteric.</li>
</ul>

<p>What I enjoy most about these (semantic) editor combinators is that their use is type-directed and so doesn&#8217;t require much imagination.
When I have the type of a complex value, and I want to edit some piece buried inside, I just read off the path in the containing type, on the way to the buried value.</p>

<p>I started writing this post last year and put it aside.
Recent threads on the <a href="http://www.haskell.org/mailman/listinfo/reactive">Reactive mailing list</a> (including a dandy <a href="http://www.haskell.org/pipermail/reactive/2008-November/000054.html">explanation by Peter Verswyvelen</a>) and on <a href="http://netsuperbrain.com/blog/">David Sankel&#8217;s blog</a> reminded me of my unfinished post, so I picked it up again.</p>

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

<ul>
<li>2008-11-29: added type of <code>v6</code> example.  Tweaked <code>inO2</code> alignment.</li>
</ul>

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

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

<h3>Example</h3>

<p>Suppose we have a value defined as follows.</p>

<pre><code>v0 :: (Int, Char -&gt; (String,Bool))
v0 = (3,  c -&gt; ([c,'q',c,'r'], isDigit c))
</code></pre>

<p>Now, how can one edit this value?
By &#8220;edit&#8221;, I simply mean to produce a value that resembles <code>v0</code> but has alterations made.</p>

<p>For concreteness, let&#8217;s say I want to reverse the string.
A programmer might answer by firing up vim, Emacs, or <a href="http://www.haskell.org/haskellwiki/Yi">yi (whee!)</a>, and change the definition to</p>

<pre><code>v0 = (3,  c -&gt; (['r',c,'q',c], isDigit c))
</code></pre>

<p>But this answer doesn&#8217;t really fit the question, which was to edit the <em>value</em>.
I want a way to edit the <em>semantics</em>, not the <em>syntax</em>, i.e., the value rather than the expression.</p>

<p>Similarly, I might want to</p>

<ul>
<li>negate the boolean,</li>
<li>double the Int,</li>
<li>swap the inner pair, or</li>
<li>swap the outer pair.</li>
</ul>

<p>Semantic editor combinators makes these tasks easy, using the following recipe, writing from left to right:</p>

<ul>
<li>Read out the path in the type of the value being edited (<code>v0</code> here), from the outside to the part to edit, naming each step, according to <em>part</em> of the type being entered, using the names &#8220;first&#8221; and &#8220;second&#8221; for pairs, and &#8220;result&#8221; for functions.</li>
<li>Write down that path as its part names, separated by periods.  If the path has at least two components, surrounded by parentheses.</li>
<li>Next write the alteration function to be applied.</li>
<li>Finally, the value being edited.</li>
</ul>

<p>In our string-reversal example, these steps look like</p>

<ul>
<li><code>(second.result.first)</code> &#8212; <em>second of the pair, result of that function, and first of that pair</em></li>
<li><code>reverse</code></li>
<li><code>v0</code></li>
</ul>

<p>So the value editing is accomplished by</p>

<pre><code>v1 = (second.result.first) reverse v0
</code></pre>

<p>Let&#8217;s see if the editing worked.
First, inspect <code>v0</code>, using GHCi:</p>

<pre><code>&gt; fst v0
3
&gt; (snd v0) 'z'
("zqzr",False)
</code></pre>

<p>and then <code>v1</code>:</p>

<pre><code>&gt; :ty v1
v1 :: (Int, Char -&gt; (String, Bool))
&gt; fst v1
3
&gt; (snd v1) 'z'
("rzqz",False)
</code></pre>

<p>The other four editings listed above are just as easy</p>

<pre><code>double x   = x+x
swap (x,y) = (y,x)

-- negate the boolean,
v2 = (second.result.second) not v0

-- double the Int,
v3 = first double v0

-- swap the inner pair, or
v4 = (second.result) swap v0

-- swap the outer pair
v5 = swap v0
</code></pre>

<p>Testing in GHCi:</p>

<pre><code>&gt; :ty v2
v2 :: (Int, Char -&gt; (String, Bool))
&gt; fst v2
3
&gt; (snd v2) 'z'
("zqzr",True)

&gt; :ty v3
v3 :: (Int, Char -&gt; (String, Bool))
&gt; fst v3
6
&gt; (snd v3) 'z'
("zqzr",False)

&gt; :ty v4
v4 :: (Int, Char -&gt; (Bool, String))
&gt; fst v4
3
&gt; (snd v4) 'z'
(False,"zqzr")

&gt; :ty v5
v5 :: (Char -&gt; (String, Bool), Int)
&gt; fst v5
&lt;interactive&gt;:1:0: No instance for (Show (Char -&gt; (String, Bool))) ...
&gt; snd v5
3
&gt; fst v5 'z'
("zqzr",False)
</code></pre>

<p>Since <code>String</code> is a synonym for <code>[Char]</code>, the type of <code>v0</code> has even more structure we can delve into:</p>

<pre><code>v0 :: (Int, Char -&gt; ([Char],Bool))
</code></pre>

<p>Add a fourth path component, <code>element</code>, for entering elements of lists.
Now we can edit the characters:</p>

<pre><code>-- previous character
v6 = (second.result.first.element) pred v0

-- character value
v7 = (second.result.first.element) ord v0
</code></pre>

<p>Testing:</p>

<pre><code>&gt; :ty v6
v6 :: (Int, Char -&gt; ([Char], Bool))
&gt; fst v6
3
&gt; (snd v6) 'z'
("ypyq",False)

&gt; :ty v7
v7 :: (Int, Char -&gt; ([Int], Bool))
&gt; fst v7
3
&gt; (snd v7) 'z'
([122,113,122,114],False)
</code></pre>

<h3>What&#8217;s going on here?</h3>

<p>You may be familiar with the functions <code>first</code> and <code>second</code>.  They&#8217;re methods on the <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Arrow.html"><code>Arrow</code> class</a>, so they&#8217;re pretty general.
When operating on <em>functions</em>, they have the following types and definitions:</p>

<pre><code>first  :: (a -&gt; a') -&gt; ((a,b) -&gt; (a',b))
second :: (b -&gt; b') -&gt; ((a,b) -&gt; (a,b'))

first  f =  (a,b) -&gt; (f a, b)
second g =  (a,b) -&gt; (a, g b)
</code></pre>

<p>Note that, as needed, <code>first</code> and <code>second</code> apply given functions to part of a pair value, carrying along the other half of the pair.</p>

<p>When working syntactically, we often apply functions under lambdas.
The corresponding value-level, embedding combinator is just function composition.
I&#8217;ll use the name <code>result</code> as a synonym for <code>(.)</code>, for consistency with <code>first</code> and <code>second</code> and, more importantly, for later generalization.</p>

<pre><code>result :: (b -&gt; b') -&gt; ((a -&gt; b) -&gt; (a -&gt; b'))
result =  (.)
</code></pre>

<p>As with <code>first</code> and <code>second</code>, I&#8217;ve used parentheses in the type signatures to emphasize the path components as being <em>unary</em>, not binary.
It&#8217;s this unusual unary view that makes <code>first</code>, <code>second</code>, and <code>result</code> (or <code>(.)</code>) composable and guides us toward composable generalizations.</p>

<p>Similarly, the <code>element</code> component is synonym for <code>fmap</code>:</p>

<pre><code>element :: (a -&gt; b) -&gt; ([a] -&gt; [b])
element = fmap
</code></pre>

<p>However, using <code>fmap</code> directly is very useful, since it encompasses <em>all</em> <code>Functor</code> types.
Since functions from any given type is a functor, I often use <code>fmap</code> in place of <code>result</code>, just to avoid having to define result.
Thanks to the <code>Functor</code> instance of pairing, we can also use <code>fmap</code> in place <code>second</code>.
(The two, however, are <a href="http://netsuperbrain.com/blog/posts/analysis-of-lazy-stream-programs/">not quite the same</a>.)
An advantage of names like <code>result</code>, <code>element</code> and <code>second</code> is that they&#8217;re more specifically descriptive.
Hence they are easier for people to read, and they lead to more helpful error messages.</p>

<h3>Found in the wild</h3>

<p>The examples above are toys I contrived to give you the basic idea.
Now I&#8217;d like to show you how very useful this technique can be in practice.</p>

<p><a href="http://haskell.org/haskellwiki/Reactive" title="Wiki page">Reactive</a> represents events via two types, <code>Future</code> and <code>Reactive</code>:</p>

<pre><code>newtype EventG t a = Event (FutureG t (ReactiveG t a))
</code></pre>

<p>The <code>Functor</code> instance uses the functor instances of <code>FutureG</code> and <code>ReactiveG</code>:</p>

<pre><code>instance Functor (EventG t) where fmap = inEvent.fmap.fmap
</code></pre>

<p>The <code>inEvent</code> functional is also a semantic editor combinator, though not so obvious from the types.
It applies a given function inside the representation of an event.</p>

<p>One pattern I use quite a lot is applying a function to the result of a curried-style multi-argument function.
For instance, <a href="http://haskell.org/haskellwiki/Reactive" title="Wiki page">Reactive</a> has a <a href="http://hackage.haskell.org/packages/archive/reactive/latest/doc/html/FRP-Reactive-Reactive.html#v%3AcountE"><code>countE</code></a> function to count event occurrences.
Each occurrence value get paired with the number of occurrences so far.</p>

<pre><code>countE :: Num n =&gt; Event b -&gt; Event (b,n)
countE = stateE 0 (+1)
</code></pre>

<p>Quite often, I use a forgetful form, <a href="(http://hackage.haskell.org/packages/archive/reactive/latest/doc/html/FRP-Reactive-Reactive.html#v%3AcountE_)"><code>countE_</code></a>, which discards the original values.
Looking at the type of <code>countE</code>, I know to direct <code>snd</code> into the <code>result</code> and then into the values of the event.
The definition follows robomatically from the type.</p>

<pre><code>countE_ :: Num n =&gt; Event b -&gt; Event n
countE_ = (result.fmap) snd countE
</code></pre>

<p>You can play this game with any number of arguments.
For instance, Reactive has <a href="http://hackage.haskell.org/packages/archive/reactive/latest/doc/html/FRP-Reactive-Behavior.html#v%3Asnapshot">a function for snaphotting behaviors on each occurrence of an event</a>, taking an initial state, state transition function, and an input event.</p>

<pre><code>snapshot :: Event a -&gt; Reactive b -&gt; Event (a,b)
</code></pre>

<p>The forgetful version descends into two results and one event, to edit the pair found there:</p>

<pre><code>snapshot_ :: Event a -&gt; Reactive b -&gt; Event b
snapshot_ = (result.result.fmap) snd snapshot
</code></pre>

<p>I could have written the following pointful version instead:</p>

<pre><code>snapshot_ e b = fmap snd (snapshot e b)
</code></pre>

<p>As a more varied example, consider these two functions:</p>

<pre><code>withRestE :: Event a -&gt; Event (a, Event a)

firstE :: Event a -&gt; a
</code></pre>

<p>The function <a href="http://hackage.haskell.org/packages/archive/reactive/latest/doc/html/FRP-Reactive-Reactive.html#v%3AwithNextE"><code>withNextE</code></a> directs <code>firstE</code> into the inner event of <code>withRestE</code>.</p>

<pre><code>withNextE :: Event a -&gt; Event (a,a)
withNextE = (result.fmap.second) firstE withRestE
</code></pre>

<h3>Who&#8217;s missing?</h3>

<p>We have <code>first</code> <code>second</code> to edit the first and second part of a pair.
We also have <code>result</code> to edit result part of a function.
We can also edit the <code>argument</code> part:</p>

<pre><code>argument :: (a' -&gt; a) -&gt; ((a -&gt; b) -&gt; (a' -&gt; b))
</code></pre>

<p>This editor combinator has a different flavor from the others, in that it is <em>contravariant</em>.
(Note the primes.)
Its definition is simple:</p>

<pre><code>argument = flip (.)
</code></pre>

<h3>Higher arity</h3>

<p>The combinators above direct unary functions into single structures.
A similar game works for n-ary functions, using the applicative functor lifters.
For instance,</p>

<pre><code>liftA2 :: (Applicative f) =&gt;
          (a -&gt; b -&gt; c) -&gt; (f a -&gt; f b -&gt; f c)
</code></pre>

<p>Since <code>liftA2</code> promotes <em>arbitrary</em> binary functions to binary functions, it can be       applied again &amp; again.</p>

<pre><code>*Main Control.Applicative&gt; :ty liftA2.liftA2.liftA2
liftA2.liftA2.liftA2 ::
  (Applicative f, Applicative g , Applicative h) =&gt;
  (a -&gt; b -&gt; c) -&gt; f (g (h a)) -&gt; f (g (h b)) -&gt; f (g (h c))
</code></pre>

<p>Similarly for <code>liftA3</code> etc.</p>

<p>Now an in-the-wild higher-arity example, taken from the <a href="http://haskell.org/haskellwiki/TypeCompose" title="Wiki page">TypeCompose</a> library.</p>

<p>Here&#8217;s a very handy way to compose two type constructors:</p>

<pre><code>newtype (g :. f) a = O { unO :: g (f a) }
</code></pre>

<p>We can apply n-ary function within <code>O</code> constructors:</p>

<pre><code>inO :: (g (f a) -&gt; g' (f' a')) -&gt; ((g :. f) a -&gt; (g' :. f') a')
inO h (O gfa) = O (h gfa)

inO2 :: ( g (f a)   -&gt;  g' (f' a')   -&gt;  g'' (f'' a''))
     -&gt; ((g :. f) a -&gt; (g' :. f') a' -&gt; (g'' :. f'') a'')
inO2 h (O gfa) (O gfa') = O (h gfa gfa')

...
</code></pre>

<p>Less pointedly,</p>

<pre><code>inO  = (  O  .) . (. unO)
inO2 = (inO  .) . (. unO)
inO3 = (inO2 .) . (. unO)
...
</code></pre>

<p>Functors compose into functors, and applicatives compose into applicatives.
(See <em><a href="http://www.soi.city.ac.uk/~ross/papers/Applicative.html" title="paper by Conor McBride and Ross Paterson">Applicative Programming with Effects</a></em>.)
The semantic-editor-combinator programming style makes these for very simple instance definitions:</p>

<pre><code>instance (Functor g, Functor f) =&gt; Functor (g :. f) where
  fmap  = inO.fmap.fmap

instance (Applicative g, Applicative f) =&gt; Applicative (g :. f) where
  pure  = O . pure . pure
  (&lt;*&gt;) = (inO2.liftA2) (&lt;*&gt;)
</code></pre>

<h3>What&#8217;s ahead?</h3>

<p>Two of our semantic editor combinators (path components) have more general types than we&#8217;ve used so far:</p>

<pre><code>first  :: Arrow (~&gt;) =&gt; (a ~&gt; a') -&gt; ((a,b) ~&gt; (a',b))
second :: Arrow (~&gt;) =&gt; (b ~&gt; b') -&gt; ((a,b) ~&gt; (a,b'))
</code></pre>

<p>I&#8217;ve simply replaced some of the <code>(-&gt;)</code>&#8216;s in the function-specific types with an arbitrary arrow type <code>(~&gt;)</code>.</p>

<p>Another post will similarly generalize <code>result</code> and then will give some nifty uses of this generalization for applying combinator-based semantic editing beyond simple values to</p>

<ul>
<li>Type representations</li>
<li>Code</li>
<li>Graphical user interfaces</li>
<li>Combinations of all of the above (including values)</li>
</ul>
<p><a href="http://conal.net/blog/?flattrss_redirect&amp;id=64&amp;md5=ade9ae9f5430ab6618064641dafbc6d4"><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/semantic-editor-combinators/feed</wfw:commentRss>
		<slash:comments>17</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%2Fsemantic-editor-combinators&amp;language=en_GB&amp;category=text&amp;title=Semantic+editor+combinators&amp;description=While+working+on+Eros%2C+I+encountered+a+function+programming+pattern+I+hadn%26%238217%3Bt+known.+I+was+struck+by+the+simplicity+and+power+of+this+pattern%2C+and+I+wondered+why+I+hadn%26%238217%3Bt...&amp;tags=applicative+functor%2Carrow%2Ccombinator%2Ceditor%2Ctechnique%2Ctype+composition%2Cblog" type="text/html" />
	</item>
		<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>
		<item>
		<title>&#8220;Tangible Functional Programming&#8221; &#8212; icfp version</title>
		<link>http://conal.net/blog/posts/tangible-functional-programming-icfp-version</link>
		<comments>http://conal.net/blog/posts/tangible-functional-programming-icfp-version#comments</comments>
		<pubDate>Tue, 10 Jul 2007 05:19:00 +0000</pubDate>
		<dc:creator><![CDATA[Conal]]></dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[arrow]]></category>
		<category><![CDATA[DeepArrow]]></category>
		<category><![CDATA[Eros]]></category>
		<category><![CDATA[gestural composition]]></category>
		<category><![CDATA[icfp]]></category>
		<category><![CDATA[interactive programming]]></category>
		<category><![CDATA[interactive visualization]]></category>
		<category><![CDATA[library]]></category>
		<category><![CDATA[Phooey]]></category>
		<category><![CDATA[TV]]></category>
		<category><![CDATA[writing]]></category>

		<guid isPermaLink="false">http://conal.net/blog/posts/tangible-functional-programming-icfp-version/</guid>
		<description><![CDATA[I just submitted the camera-ready version of &#8220;Tangible Functional Programming&#8221;, for ICFP &#8217;07. I&#8217;m happy with this version. It&#8217;s improved drastically since my first submission to ICFP &#8217;06, thanks to many helpful comments. I&#8217;ve also been recreating the implementation on top of DeepArrow, Phooey, and TV, in preparation for a software release. It&#8217;s getting simpler, [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>I just submitted the camera-ready version of <a href="http://conal.net/papers/Eros">&#8220;Tangible Functional Programming&#8221;</a>, for <a href="http://www.informatik.uni-bonn.de/%7Eralf/icfp07.html">ICFP &#8217;07</a>.  I&#8217;m happy with this version. It&#8217;s improved drastically since my first submission to ICFP &#8217;06, thanks to many helpful comments. I&#8217;ve also been recreating the implementation on top of <a href="http://www.haskell.org/haskellwiki/DeepArrow">DeepArrow</a>, <a href="http://www.haskell.org/haskellwiki/Phooey">Phooey</a>, and <a href="http://www.haskell.org/haskellwiki/TV">TV</a>, in preparation for a software release. It&#8217;s getting simpler, but it&#8217;s not as simple as I want.</p>
<p><a href="http://conal.net/blog/?flattrss_redirect&amp;id=37&amp;md5=9870e5dd6003b96b97a04f322c179426"><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/tangible-functional-programming-icfp-version/feed</wfw:commentRss>
		<slash:comments>0</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%2Ftangible-functional-programming-icfp-version&amp;language=en_GB&amp;category=text&amp;title=%26%238220%3BTangible+Functional+Programming%26%238221%3B+%26%238212%3B+icfp+version&amp;description=I+just+submitted+the+camera-ready+version+of+%26%238220%3BTangible+Functional+Programming%26%238221%3B%2C+for+ICFP+%26%238217%3B07.+I%26%238217%3Bm+happy+with+this+version.+It%26%238217%3Bs+improved+drastically+since+my+first+submission+to+ICFP+%26%238217%3B06%2C+thanks+to...&amp;tags=arrow%2CDeepArrow%2CEros%2Cgestural+composition%2Cicfp%2Cinteractive+programming%2Cinteractive+visualization%2Clibrary%2CPhooey%2CTV%2Cwriting%2Cblog" type="text/html" />
	</item>
	</channel>
</rss>
