<?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; FRP</title>
	<atom:link href="http://conal.net/blog/tag/frp/feed/" rel="self" type="application/rss+xml" />
	<link>http://conal.net/blog</link>
	<description>Inspirations &#38; experiments, mainly about denotational programming in Haskell</description>
	<lastBuildDate>Fri, 30 Jul 2010 02:56:11 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Garbage collecting the semantics of FRP</title>
		<link>http://conal.net/blog/posts/garbage-collecting-the-semantics-of-frp/</link>
		<comments>http://conal.net/blog/posts/garbage-collecting-the-semantics-of-frp/#comments</comments>
		<pubDate>Mon, 04 Jan 2010 21:55:30 +0000</pubDate>
		<dc:creator>conal</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[derivative]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[FRP]]></category>
		<category><![CDATA[functional reactive programming]]></category>
		<category><![CDATA[semantics]]></category>

		<guid isPermaLink="false">http://conal.net/blog/?p=96</guid>
		<description><![CDATA[]]></description>
			<content:encoded><![CDATA[<!-- 

Title: Garbage collecting the semantics of FRP

Tags: FRP, functional reactive programming, semantics, design, derivative

URL: http://conal.net/blog/posts/garbage-collecting-the-semantics-of-frp/

-->

<!-- references -->

<!-- teaser -->

<p>Ever since <a href="http://conal.net/papers/ActiveVRML/" title="Tech report: &quot;A Brief Introduction to ActiveVRML&quot;">ActiveVRML</a>, the model we&#8217;ve been using in functional reactive programming (FRP) for interactive behaviors is <code>(T-&gt;a) -&gt; (T-&gt;b)</code>, for dynamic (time-varying) input of type <code>a</code> and dynamic output of type <code>b</code> (where <code>T</code> is time).
In &#8220;Classic FRP&#8221; formulations (including <a href="http://conal.net/papers/ActiveVRML/" title="Tech report: &quot;A Brief Introduction to ActiveVRML&quot;">ActiveVRML</a>, <a href="http://conal.net/papers/icfp97/" title="paper">Fran</a> &amp; <a href="http://conal.net/papers/push-pull-frp/" title="Paper by Conal Elliott and Paul Hudak">Reactive</a>), there is a &#8220;behavior&#8221; abstraction whose denotation is a function of time.
Interactive behaviors are then modeled as host language (e.g., Haskell) functions between behaviors.
Problems with this formulation are described in <em><a href="http://conal.net/blog/posts/why-classic-FRP-does-not-fit-interactive-behavior/" title="blog post">Why classic FRP does not fit interactive behavior</a></em>.
These same problems motivated &#8220;Arrowized FRP&#8221;.
In Arrowized FRP, behaviors (renamed &#8220;signals&#8221;) are purely conceptual.
They are part of the semantic model but do not have any realization in the programming interface.
Instead, the abstraction is a <em>signal transformer</em>, <code>SF a b</code>, whose semantics is <code>(T-&gt;a) -&gt; (T-&gt;b)</code>.
See <em><a href="http://conal.net/papers/genuinely-functional-guis.pdf" title="Paper by Antony Courtney and Conal Elliott">Genuinely Functional User Interfaces</a></em> and <em><a href="http://www.haskell.org/yale/papers/haskellworkshop02/" title="Paper by Henrik Nilsson, Antony Courtney, and John Peterson">Functional Reactive Programming, Continued</a></em>.</p>

<p>Whether in its classic or arrowized embodiment, I&#8217;ve been growing uncomfortable with this semantic model of functions between time functions.
A few weeks ago, I realized that one source of discomfort is that this model is <em>mostly junk</em>.</p>

<p>This post contains some partially formed thoughts about how to eliminate the junk (&#8220;garbage collect the semantics&#8221;), and what might remain.</p>

<!--
**Edits**:

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

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

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

<p>There are two generally desirable properties for a denotational semantics: <em>full abstraction</em> and <em>junk-freeness</em>.
Roughly, &#8220;full abstraction&#8221; means we must not distinguish between what is (operationally) indistinguishable, while &#8220;junk-freeness&#8221; means that every semantic value must be denotable.</p>

<p>FRP&#8217;s semantic model, <code>(T-&gt;a) -&gt; (T-&gt;b)</code>, allows not only arbitrary (computable) transformation of input values, but also of time.
The output at some time can depend on the input at any time at all, or even on the input at arbitrarily many different times.
Consequently, this model allows respoding to <em>future</em> input, violating a principle sometimes called &#8220;causality&#8221;, which is that outputs may depend on the past or present but not the future.</p>

<p>In a causal system, the present can reach backward to the past but not forward the future.
I&#8217;m uneasy about this ability as well.
Arbitrary access to the past may be much more powerful than necessary.
As evidence, consult the system we call (physical) Reality.
As far as I can tell, Reality operates without arbitrary access to the past or to the future, and it does a pretty good job at expressiveness.</p>

<p>Moreover, arbitrary past access is also problematic to implement in its semantically simple generality.</p>

<p>There is a thing we call informally &#8220;memory&#8221;, which at first blush may look like access to the past, it isn&#8217;t really.
Rather, memory is access to a <em>present</em> input, which has come into being through a process of filtering, gradual accumulation, and discarding (forgetting).
I&#8217;m talking about &#8220;memory&#8221; here in the sense of what our brains do, but also what all the rest of physical reality does.
For instance, weather marks on a rock are part of the rock&#8217;s (present) memory of the past weather.</p>

<p>A very simple memory-less semantic model of interactive behavior is just <code>a -&gt; b</code>.
This model is too restrictive, however, as it cannot support <em>any</em> influence of the past on the present.</p>

<p>Which leaves a question: what is a simple and adequate formal model of interactive behavior that reaches neither into the past nor into the future, and yet still allows the past to influence the present?
Inspired in part by a design principle I call &#8220;what would reality do?&#8221; (WWRD), I&#8217;m happy to have some kind of infinitesimal access to the past, but nothing further.</p>

<p>My current intuition is that differentiation/integration plays a crucial role.
That information is carried forward moment by moment in time as &#8220;momentum&#8221; in some sense.</p>

<blockquote>
  <p><em>I call intuition cosmic fishing. You feel a nibble, then you&#8217;ve got to hook the fish.</em> &#8211; Buckminster Fuller</p>
</blockquote>

<p>Where to go with these intuitions?</p>

<p>Perhaps interactive behaviors are some sort of function with all of its derivatives.
See <em><a href="http://conal.net/blog/posts/beautiful-differentiation/" title="blog post">Beautiful differentiation</a></em> for an specification and derived implementation of numeric operations, and more generally of <code>Functor</code> and <code>Applicative</code>, on which much of FRP is based.</p>

<p>I suspect the whole event model can be replaced by integration.
Integration is the main remaining piece.</p>

<p>How weak a semantic model can let us define integration?</p>

<h3>Thanks</h3>

<p>My thanks to Luke Palmer and to Noam Lewis for some clarifying chats about these half-baked ideas.
And to the folks on #haskell IRC for <a href="http://tunes.org/~nef/logs/haskell/10.01.04">brainstorming titles for this post</a>.
My favorite suggestions were</p>

<ul>
<li>luqui: instance HasJunk FRP where</li>
<li>luqui: Functional reactive programming&#8217;s semantic baggage</li>
<li>sinelaw: FRP, please take out the trash!</li>
<li>cale: Garbage collecting the semantics of FRP</li>
<li>BMeph: Take out the FRP-ing Trash</li>
</ul>

<p>all of which I preferred over my original &#8220;FRP is mostly junk&#8221;.</p>
]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/garbage-collecting-the-semantics-of-frp/feed/</wfw:commentRss>
		<slash:comments>30</slash:comments>
		</item>
		<item>
		<title>3D rendering as functional reactive programming</title>
		<link>http://conal.net/blog/posts/3d-rendering-as-functional-reactive-programming/</link>
		<comments>http://conal.net/blog/posts/3d-rendering-as-functional-reactive-programming/#comments</comments>
		<pubDate>Mon, 12 Jan 2009 05:38:58 +0000</pubDate>
		<dc:creator>conal</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[3D]]></category>
		<category><![CDATA[FRP]]></category>
		<category><![CDATA[functional reactive programming]]></category>
		<category><![CDATA[monoid]]></category>
		<category><![CDATA[semantics]]></category>

		<guid isPermaLink="false">http://conal.net/blog/?p=75</guid>
		<description><![CDATA[]]></description>
			<content:encoded><![CDATA[<!-- 

Title: 3D rendering as functional reactive programming

Tags: 3D, semantics, FRP, functional reactive programming, monoid

nURL: http://conal.net/blog/posts/3d-rendering-as-functional-reactive-programming/

-->

<!-- references -->

<!-- teaser -->

<p>I&#8217;ve been playing with a simple/general semantics for 3D.
In the process, I was surprised to see that a key part of the semantics looks exactly like a key part of the semantics of functional reactivity as embodied in the library <em><a href="http://haskell.org/haskellwiki/Reactive" title="Wiki page for the Reactive library">Reactive</a></em>.
A closer look revealed a closer connection still, as described in this post.</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-75"></span></p>

<h3>What is 3D rendering?</h3>

<p>Most programmers think of 3D rendering as being about executing sequence of side-effects on frame buffer or some other mutable array of pixels.
This way of thinking (sequences of side-effects) comes to us from the design of early sequential computers.
Although computer hardware architecture has evolved a great deal, most programming languages, and hence most programming thinking, is still shaped by the this first sequential model.
(See John Backus&#8217;s Turing Award lecture <em><a href="www.stanford.edu/class/cs242/readings/backus.pdf" title="Turing Award lecture by John Backus">Can Programming Be Liberated from the von Neumann Style?  A functional style and its algebra of programs</a></em>.)
The invention of monadic <em><a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.53.2504" title="paper by Simon Peyton Jones and Philip Wadler">Imperative functional programming</a></em> allows Haskellers to think and program within the imperative paradigm as well.</p>

<p>What&#8217;s a <em>functional</em> alternative?
Rendering is a function from something to something else.
Let&#8217;s call these somethings (3D) &#8220;Geometry&#8221; and (2D) &#8220;Image&#8221;, where <code>Geometry</code> and <code>Image</code> are types of functional (immutable) values.</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">type</span> Rendering = Image Color
&nbsp;
render :: Geometry -&gt; Rendering</pre>
</div></p>

<p>To simplify, I&#8217;m assuming a fixed view.
What remains is to define what these two types <em>mean</em> and, secondarily, how to represent and implement them.</p>

<p>An upcoming post will suggest an answer for the meaning of <code>Geometry</code>.
For now, think of it as a collection of curved and polygonal surfaces, i.e., the <em>outsides</em> (boundaries) of solid shapes.
Each point on these surfaces has a location, a normal (perpendicular direction), and material properties (determining how light is reflected by and transmitted through the surface at the point).
The geometry will contain light sources.</p>

<p>Next, what is the meaning of <code>Image</code>?
A popular answer is that an image is a rectangular array of finite-precision encodings of color (e.g., with eight bits for each of red, blue, green and possibly opacity).
This answer is leads to poor compositionality and complex meanings for operations like scaling and rotation, so I prefer another model.
As in <a href="http://conal.net/Pan" title="project web page">Pan</a>, an image (the meaning of the type <code>Image Color</code>) is a function from infinite continuous 2D space to colors, where the <code>Color</code> type includes partial opacity.
For motivation of this model and examples of its use, see <em><a href="http://conal.net/papers/functional-images/" title="book chapter">Functional images</a></em> and the corresponding <a href="http://conal.net/Pan/Gallery" title="gallery of functional images">Pan gallery</a> of functional images.
<em>Composition</em> occurs on infinite &amp; continuous images.</p>

<p>After all composition is done, the resulting image can be sampled into a finite, rectangular array of finite precision color encodings.
I&#8217;m talking about a conceptual/semantic pipeline.
The implementation computes the finite sampling without having to compute the values for entire infinite image.</p>

<p>Rendering has several components.
I&#8217;ll just address one and show how it relates to functional reactive programming (FRP).</p>

<h3>Visual occlusion</h3>

<p>One aspect of 3D rendering is <a href="en.wikipedia.org/wiki/Hidden_surface_determination">hidden surface determination</a>.
Relative to the viewer&#8217;s position and orientation, some 3D objects may fully or partially occluded by nearer objects.</p>

<p>An image is a function of (infinite and continuous) 2D space, so specifying that function is determining its value at every sample point.
Each point can correspond to a number of geometric objects, some closer and some further.
If we assume for now that our colors are fully opaque, then we&#8217;ll need to know the color (after transformation and lighting) of the <em>nearest</em> surface point that is projected onto the sample point.
(We&#8217;ll remove this opacity assumption later.)</p>

<p>Let&#8217;s consider how we&#8217;ll combine two <code>Geometry</code> values into one:</p>

<p><div>
<pre class="haskell">union :: Geometry -&gt; Geometry -&gt; Geometry</pre>
</div></p>

<p>Because of occlusion, the <code>render</code> function cannot be compositional with respect to <code>union</code>.
If it were, then there would exist a functions <code>unionR</code> such that</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">forall</span> ga gb. render <span style="color: green;">&#40;</span>ga `union` gb<span style="color: green;">&#41;</span> == render ga `unionR` render gb</pre>
</div></p>

<p>In other words, to render a union of two geometries, we can render each and combine the results.</p>

<p>The reason we can&#8217;t find such a <code>unionR</code> is that <code>render</code> doesn&#8217;t let <code>unionR</code> know how close each colored point is.
A solution then is simple: add in the missing depth information:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">type</span> RenderingD = Image <span style="color: green;">&#40;</span>Depth, Color<span style="color: green;">&#41;</span>  <span style="color: #5d478b; font-style: italic;">-- first try</span>
&nbsp;
renderD :: Geometry -&gt; RenderingD</pre>
</div></p>

<p>Now we have enough information for compositional rendering, i.e., we can define <code>unionR</code> such that</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">forall</span> ga gb. renderD <span style="color: green;">&#40;</span>ga `union` gb<span style="color: green;">&#41;</span> == renderD ga `unionR` renderD gb</pre>
</div></p>

<p>where</p>

<p><div>
<pre class="haskell">unionR :: RenderingD -&gt; RenderingD -&gt; RenderingD
&nbsp;
unionR im im' p = <span style="color: #050; font-weight: bold;">if</span> d &lt;= d' <span style="color: #050; font-weight: bold;">then</span> <span style="color: green;">&#40;</span>d,c<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">else</span> <span style="color: green;">&#40;</span>d',c'<span style="color: green;">&#41;</span>
 <span style="color: #050; font-weight: bold;">where</span>
   <span style="color: green;">&#40;</span>d ,c <span style="color: green;">&#41;</span> = im  p
   <span style="color: green;">&#40;</span>d',c'<span style="color: green;">&#41;</span> = im' p</pre>
</div></p>

<p>When we&#8217;re done composing, we can discard the depths:</p>

<p><div>
<pre class="haskell">render g = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:snd"><span style="font-weight: bold;">snd</span></a> . renderD g</pre>
</div></p>

<p>or, with <em><a href="http://conal.net/blog/posts/semantic-editor-combinators/" title="blog post">Semantic editor combinators</a></em>:</p>

<p><div>
<pre class="haskell">render = <span style="color: green;">&#40;</span>result.result<span style="color: green;">&#41;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:snd"><span style="font-weight: bold;">snd</span></a> renderD</pre>
</div></p>

<h3>Simpler, prettier</h3>

<p>The <code>unionR</code> is not very complicated, but still, I like to tease out common structure and reuse definitions wherever I can.
The first thing I notice about <code>unionR</code> is that it works pointwise.
That is, the value at a point is a function of the values of two other images at the same point.
The pattern is captured by <code>liftA2</code> on functions, thanks to the <code>Applicative</code> instance for functions.</p>

<p><div>
<pre class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:liftA2"><span style="font-weight: bold;">liftA2</span></a> :: <span style="color: green;">&#40;</span>b -&gt; c -&gt; d<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>a -&gt; b<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>a -&gt; c<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>a -&gt; d<span style="color: green;">&#41;</span></pre>
</div></p>

<p>So that</p>

<p><div>
<pre class="haskell">unionR = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:liftA2"><span style="font-weight: bold;">liftA2</span></a> closer
&nbsp;
closer <span style="color: green;">&#40;</span>d,c<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>d',c'<span style="color: green;">&#41;</span> = <span style="color: #050; font-weight: bold;">if</span> d &lt;= d' <span style="color: #050; font-weight: bold;">then</span> <span style="color: green;">&#40;</span>d,c<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">else</span> <span style="color: green;">&#40;</span>d',c'<span style="color: green;">&#41;</span></pre>
</div></p>

<p>Or</p>

<p><div>
<pre class="haskell">closer dc@<span style="color: green;">&#40;</span>d,_<span style="color: green;">&#41;</span> dc'@<span style="color: green;">&#40;</span>d',_<span style="color: green;">&#41;</span> = <span style="color: #050; font-weight: bold;">if</span> d &lt;= d' <span style="color: #050; font-weight: bold;">then</span> dc <span style="color: #050; font-weight: bold;">else</span> dc'</pre>
</div></p>

<p>Or even</p>

<p><div>
<pre class="haskell">closer = minBy <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fst"><span style="font-weight: bold;">fst</span></a></pre>
</div></p>

<p>where</p>

<p><div>
<pre class="haskell">minBy f u v = <span style="color: #050; font-weight: bold;">if</span> f u &lt;= f v <span style="color: #050; font-weight: bold;">then</span> u <span style="color: #050; font-weight: bold;">else</span> v</pre>
</div></p>

<p>This definition of <code>unionR</code> is not only simpler, it&#8217;s quite a bit more general, as type inference reveals:</p>

<p><div>
<pre class="haskell">unionR :: <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> a, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#t:Applicative"><span style="color: #833; font-weight: bold;">Applicative</span></a> f<span style="color: green;">&#41;</span> =&gt; f <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> -&gt; f <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> -&gt; f <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span>
&nbsp;
closer :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> a =&gt; <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span></pre>
</div></p>

<p>Once again, simplicity and generality go hand-in-hand.</p>

<h3>Another type class morphism</h3>

<p>Let&#8217;s see if we can make <code>union</code> rendering simpler and more inevitable.
Rendering is <em>nearly</em> a homomorphism.
That is, <code>render</code> nearly distributes over <code>union</code>, but we have to replace <code>union</code> by <code>unionR</code>.
I&#8217;d rather eliminate this discrepancy, ending up with</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">forall</span> ga gb. renderD <span style="color: green;">&#40;</span>ga `op` gb<span style="color: green;">&#41;</span> == renderD ga `op` renderD gb</pre>
</div></p>

<p>for some <code>op</code> that is equal to <code>union</code> on the left and <code>unionR</code> on the right.
Since <code>union</code> and <code>unionR</code> have different types (with neither being a polymorphic instance of the other), <code>op</code> will have to be a method of some type class.</p>

<p>My favorite binary method is <code>mappend</code>, from <code>Monoid</code>, so let&#8217;s give it a try.
<code>Monoid</code> requires there also to be an identity element <code>mempty</code> and that <code>mappend</code> be associative.
For <code>Geometry</code>, we can define</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> Geometry <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>  = emptyGeometry
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a> = union</pre>
</div></p>

<p>Images with depth are a little trickier.
Image already has a <code>Monoid</code> instance, whose semantics is determined by the principle of <a href="http://conal.net/blog/tag/type-class-morphism/" title="Posts on type class morphisms">type class morphisms</a>, namely</p>

<blockquote>
  <p><em>The meaning of an instance is the instance of the meaning</em></p>
</blockquote>

<p>The meaning of an image is a function, and that functions have a <code>Monoid</code> instance:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> b =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> <span style="color: green;">&#40;</span>a -&gt; b<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>
  f `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` g = \ a -&gt; f a `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` g a</pre>
</div></p>

<p>which simplifies nicely to a standard form, by using the <code>Applicative</code> instance for functions.</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#t:Applicative"><span style="color: #833; font-weight: bold;">Applicative</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>-&gt;<span style="color: green;">&#41;</span> a<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a>      = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a>
  hf &lt;*&gt; xf = \ a -&gt; <span style="color: green;">&#40;</span>hf a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>xf a<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> b =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> <span style="color: green;">&#40;</span>a -&gt; b<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>  = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a>   <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:liftA2"><span style="font-weight: bold;">liftA2</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a></pre>
</div></p>

<p>We&#8217;re in luck.
Since we&#8217;ve defined <code>unionR</code> as <code>liftA2 closer</code>, so we just need it to turn out that <code>closer == mappend</code> and that <code>closer</code> is associative and has an identity element.</p>

<p>However, <code>closer</code> is defined on pairs, and the standard <code>Monoid</code> instance on pairs doesn&#8217;t fit.</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> a, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> b<span style="color: green;">&#41;</span> =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a> = <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>,<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a><span style="color: green;">&#41;</span>
  <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` <span style="color: green;">&#40;</span>a',b'<span style="color: green;">&#41;</span> = <span style="color: green;">&#40;</span>a `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` a', b `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` b'<span style="color: green;">&#41;</span></pre>
</div></p>

<p>To avoid this conflict, define a new data type to be used in place of pairs.</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">data</span> DepthG d a = Depth d a  <span style="color: #5d478b; font-style: italic;">-- first try</span></pre>
</div></p>

<p>Alternatively,</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">newtype</span> DepthG d a = Depth <span style="color: green;">&#123;</span> unDepth :: <span style="color: green;">&#40;</span>d,a<span style="color: green;">&#41;</span> <span style="color: green;">&#125;</span></pre>
</div></p>

<p>I&#8217;ll go with this latter version, as it turns out to be more convenient.</p>

<p>Then we can define our monoid:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> <span style="color: green;">&#40;</span>DepthG d a<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>  = Depth <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:maxBound"><span style="font-weight: bold;">maxBound</span></a>,<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:undefined"><span style="font-weight: bold;">undefined</span></a><span style="color: green;">&#41;</span>
  Depth p `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` Depth p' = Depth <span style="color: green;">&#40;</span>p `closer` p'<span style="color: green;">&#41;</span></pre>
</div></p>

<p>The second method definition can be simplified nicely</p>

<p><div>
<pre class="haskell">  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a> = inDepth2 closer</pre>
</div></p>

<p>where</p>

<p><div>
<pre class="haskell">  inDepth2 = unDepth ~&gt; unDepth ~&gt; Depth</pre>
</div></p>

<p>using the ideas from <em><a href="http://conal.net/blog/posts/prettier-functions-for-wrapping-and-wrapping/" title="blog post">Prettier functions for wrapping and wrapping</a></em> and the notational improvement from Matt Hellige&#8217;s <em><a href="http://matt.immute.net/content/pointless-fun" title="blog post by Matt Hellige">Pointless fun</a></em>.</p>

<h3>FRP &#8212; Future values</h3>

<p>The <code>Monoid</code> instance for <code>Depth</code> may look familiar to you if you&#8217;ve been following along with my <a href="http://conal.net/blog/tag/future-value/" title="Posts on futures values">future value</a>s or have read the paper <em><a href="http://conal.net/papers/simply-reactive" title="Paper: &quot;Simply efficient functional reactivity&quot;">Simply efficient functional reactivity</a></em>.
A <em>future value</em> has a time and a value.
Usually, the value cannot be known until its time arrives.</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">newtype</span> FutureG t a = Future <span style="color: green;">&#40;</span>Time t, a<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #050; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> t, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bounded"><span style="color: #833; font-weight: bold;">Bounded</span></a> t<span style="color: green;">&#41;</span> =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> <span style="color: green;">&#40;</span>FutureG t a<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a> = Future <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:maxBound"><span style="font-weight: bold;">maxBound</span></a>, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:undefined"><span style="font-weight: bold;">undefined</span></a><span style="color: green;">&#41;</span>
  Future <span style="color: green;">&#40;</span>s,a<span style="color: green;">&#41;</span> `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` Future <span style="color: green;">&#40;</span>t,b<span style="color: green;">&#41;</span> =
    Future <span style="color: green;">&#40;</span>s `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:min"><span style="font-weight: bold;">min</span></a>` t, <span style="color: #050; font-weight: bold;">if</span> s &lt;= t <span style="color: #050; font-weight: bold;">then</span> a <span style="color: #050; font-weight: bold;">else</span> b<span style="color: green;">&#41;</span></pre>
</div></p>

<p>When we&#8217;re using a non-lazy (flat) representation of time, this <code>mappend</code> definition can be written more simply:</p>

<p><div>
<pre class="haskell">  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a> = minBy futTime
&nbsp;
  futTime <span style="color: green;">&#40;</span>Future <span style="color: green;">&#40;</span>t,_<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> = t</pre>
</div></p>

<p>Equivalently,</p>

<p><div>
<pre class="haskell">  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a> = inFuture2 <span style="color: green;">&#40;</span>minBy <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fst"><span style="font-weight: bold;">fst</span></a><span style="color: green;">&#41;</span></pre>
</div></p>

<p>The <code>Time</code> type is really nothing special about time.
It is just a synonym for the <a href="http://hackage.haskell.org/packages/archive/reactive/latest/doc/html/Data-Max.html" title="module documentation"><code>Max</code> monoid</a>, as needed for the <code>Applicative</code> and <code>Monad</code> instances.</p>

<p>This connection with future values means we can discard more code.</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">type</span> RenderingD d = Image <span style="color: green;">&#40;</span>FutureG d Color<span style="color: green;">&#41;</span>
renderD :: <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> d, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bounded"><span style="color: #833; font-weight: bold;">Bounded</span></a> d<span style="color: green;">&#41;</span> =&gt; Geometry -&gt; RenderingD d</pre>
</div></p>

<p>Now we have our monoid (homo)morphism properties:</p>

<p><div>
<pre class="haskell">renderD <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a> == <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>
&nbsp;
renderD <span style="color: green;">&#40;</span>ga `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` gb<span style="color: green;">&#41;</span> == renderD ga `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` renderD gb</pre>
</div></p>

<p>And we&#8217;ve eliminated the code for <code>renderR</code> by reusing and existing type (future values).</p>

<h3>Future values?</h3>

<p>What does it mean to think about depth/color pairs as being &#8220;future&#8221; colors?
If we were to probe outward along a ray, say at the speed of light, we would bump into some number of 3D objects.
The one we hit earliest is the nearest, so in this sense, <code>mappend</code> on futures (choosing the earlier one) is the right tool for the job.</p>

<p>I once read that a popular belief in the past was that vision (light) reaches outward to strike objects, as I&#8217;ve just described.
I&#8217;ve forgotten where I read about that belief, though I think in a book about perspective, and I&#8217;d appreciate a pointer from someone else who might have a reference.</p>

<p>We moderns believe that light travels to us from the objects we see.
What we see of nearby objects comes from the very recent past, while of further objects we see the more remote past.
From this modern perspective, therefore, the connection I&#8217;ve made with future values is exactly backward.
Now that I think about it in this way, of course it&#8217;s backward, because we see (slightly) into the past rather than the future.</p>

<p>Fixing this conceptual flaw is simple: define a type of &#8220;past values&#8221;.
Give them exactly the same representation as future values, and deriving its class instances entirely.</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">newtype</span> PastG t a = Past <span style="color: green;">&#40;</span>FutureG t a<span style="color: green;">&#41;</span>
  <span style="color: #050; font-weight: bold;">deriving</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a>, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="color: #833; font-weight: bold;">Functor</span></a>, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#t:Applicative"><span style="color: #833; font-weight: bold;">Applicative</span></a>, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="color: #833; font-weight: bold;">Monad</span></a><span style="color: green;">&#41;</span></pre>
</div></p>

<p>Alternatively, choose a temporally neutral replacement for the name &#8220;future values&#8221;.</p>

<h3>The bug in Z-buffering</h3>

<p>The <code>renderD</code> function implements continuous, infinite Z-buffering, with <code>mappend</code> performing the z-compare and conditional overwrite.
Z-buffering is the dominant algorithm used in real-time 3D graphics and is supported in hardware on even low-end graphics hardware (though not in its full continuous and infinite glory).</p>

<p>However, Z-buffering also has a serious bug: it is only correct for fully opaque colors.
Consider a geometry <code>g</code> and a point <code>p</code> in the domain of the result image.
There may be many different points in <code>g</code> that project to <code>p</code>.
If <code>g</code> has only fully opaque colors, then at most one place on <code>g</code> contributes to the rendered image at <code>p</code>, and specifically, the nearest such point.
If <code>g</code> is the <code>union</code> (<code>mappend</code>) of two other geometries, <code>g == ga `union` gb</code>, then the nearest contribution of <code>g</code> (for <code>p</code>) will be the nearer (<code>mappend</code>) of the nearest contributions of <code>ga</code> and of <code>gb</code>.</p>

<p>When colors may be <em>partially</em> opaque, the color of the rendering at a point <code>p</code> can depend on <em>all</em> of the points in the geometry that get projected to <code>p</code>.
Correct rendering in the presence of partial opacity requires a <code>fold</code> that combines all of the colors that project onto a point, <em>in order of distance</em>, where the color-combining function (alpha-blending) is <em>not</em> commutative.
Consider again <code>g == ga `union` gb</code>.
The contributions of <code>ga</code> to <code>p</code> might be entirely closer than the contributions of <code>gb</code>, or entirely further, or interleaved.
If interleaved, then the colors generated from each cannot be combined into a single color for further combination.
To handle the general case, replace the single distance/color pair with an ordered <em>collection</em> of them:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">type</span> RenderingD d = Image <span style="color: green;">&#91;</span>FutureG d Color<span style="color: green;">&#93;</span>  <span style="color: #5d478b; font-style: italic;">-- multiple projections, first try</span></pre>
</div></p>

<p>Rendering a <code>union</code> (<code>mappend</code>) requires a merging of two lists of futures (distance/color pairs) into a single one.</p>

<h3>More FRP &#8212; Events</h3>

<p>Sadly, we&#8217;ve now lost our monoid morphism, because list <code>mappend</code> is <code>(++)</code>, not the required merging.
However, we can fix this problem as we did before, by introducing a new type.</p>

<p>Or, we can look for an existing type that matches our required semantics.
There is just such a thing in the <em><a href="http://haskell.org/haskellwiki/Reactive" title="Wiki page for the Reactive library">Reactive</a></em> formulation of FRP, namely an <em>event</em>.
We can simply use the FRP <code>Event</code> type:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">type</span> RenderingD d = Image <span style="color: green;">&#40;</span>EventG d Color<span style="color: green;">&#41;</span>
&nbsp;
renderD :: <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> d, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bounded"><span style="color: #833; font-weight: bold;">Bounded</span></a> d<span style="color: green;">&#41;</span> =&gt; Geometry -&gt; RenderingD d</pre>
</div></p>

<h3>Spatial transformation</h3>

<p>Introducing depths allowed rendering to be defined compositionally with respect to geometric union.
Is the depth model, enhanced with lists (events), sufficient for compositionality of rendering with respect to other <code>Geometry</code> operations as well?
Let&#8217;s look at spatial transformation.</p>

<p><div>
<pre class="haskell"><span style="color: green;">&#40;</span>*%<span style="color: green;">&#41;</span>  :: Transform3 -&gt; Geometry -&gt; Geometry</pre>
</div></p>

<p>Compositionally of rendering would mean that we can render <code>xf *% g</code> by rendering <code>g</code> and then using <code>xf</code> in some way to transform that rendering.
In other words there would have to exist a function <code>(*%%)</code> such that</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">forall</span> xf g. renderD <span style="color: green;">&#40;</span>xf *% g<span style="color: green;">&#41;</span> == xf *%% renderD g</pre>
</div></p>

<p>I don&#8217;t know if the required <code>(*%%)</code> function exists, or what restrictions on <code>Geometry</code> or <code>Transform3</code> it implies, or whether such a function could be useful in practice.
Instead, let&#8217;s change the type of renderings again, so that rendering can accumulate transformations and apply them to surfaces.</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">type</span> RenderingDX = Transform3 -&gt; RenderingD
&nbsp;
renderDX :: <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> d, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bounded"><span style="color: #833; font-weight: bold;">Bounded</span></a> d<span style="color: green;">&#41;</span> =&gt; Geometry -&gt; RenderingDX d</pre>
</div></p>

<p>with or without correct treatment of partial opacity (i.e., using futures or events).</p>

<p>This new function has a simple specification:</p>

<p><div>
<pre class="haskell">renderDX g xf == renderD <span style="color: green;">&#40;</span>xf *% g<span style="color: green;">&#41;</span></pre>
</div></p>

<p>from which it follows that</p>

<p><div>
<pre class="haskell">renderD g == renderDX g identityX</pre>
</div></p>

<p>Rendering a transformed geometry then is a simple accumulation, justified as follows:</p>

<p><div>
<pre class="haskell">renderDX <span style="color: green;">&#40;</span>xfi *% g<span style="color: green;">&#41;</span>
&nbsp;
  == <span style="color: #5d478b; font-style: italic;">{- specification of renderDX -}</span>
&nbsp;
\ xfo -&gt; renderD <span style="color: green;">&#40;</span>xfo *% <span style="color: green;">&#40;</span>xfi *% g<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
  == <span style="color: #5d478b; font-style: italic;">{- property of transformation -}</span>
&nbsp;
\ xfo -&gt; renderD <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>xfo `composeX` xfi<span style="color: green;">&#41;</span> *% g<span style="color: green;">&#41;</span>
&nbsp;
  == <span style="color: #5d478b; font-style: italic;">{- specification of renderDX  -}</span>
&nbsp;
\ xfo -&gt; renderDX g <span style="color: green;">&#40;</span>xfo `composeX` xfi<span style="color: green;">&#41;</span></pre>
</div></p>

<p>Render an empty geometry:</p>

<p><div>
<pre class="haskell">renderDX <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>
&nbsp;
  == <span style="color: #5d478b; font-style: italic;">{- specification of renderDX -}</span>
&nbsp;
\ xf -&gt; renderD <span style="color: green;">&#40;</span>xf *% <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a><span style="color: green;">&#41;</span>
&nbsp;
  == <span style="color: #5d478b; font-style: italic;">{- property of (*%) and mempty -}</span>
&nbsp;
\ xf -&gt; renderD <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>
&nbsp;
  == <span style="color: #5d478b; font-style: italic;">{- renderD is a monoid morphism -}</span>
&nbsp;
\ xf -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>
&nbsp;
  == <span style="color: #5d478b; font-style: italic;">{- definition of pure on functions -}</span>
&nbsp;
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>
&nbsp;
  == <span style="color: #5d478b; font-style: italic;">{- definition of mempty on functions -}</span>
&nbsp;
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a></pre>
</div></p>

<p>Render a geometric union:</p>

<p><div>
<pre class="haskell">renderDX <span style="color: green;">&#40;</span>ga `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` gb<span style="color: green;">&#41;</span>
&nbsp;
  == <span style="color: #5d478b; font-style: italic;">{- specification of renderDX -}</span>
&nbsp;
\ xf -&gt; renderD <span style="color: green;">&#40;</span>xf *% <span style="color: green;">&#40;</span>ga `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` gb<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
  == <span style="color: #5d478b; font-style: italic;">{- property of transformation and union -}</span>
&nbsp;
\ xf -&gt; renderD <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>xf *% ga<span style="color: green;">&#41;</span> `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` <span style="color: green;">&#40;</span>xf *% gb<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
  == <span style="color: #5d478b; font-style: italic;">{- renderD is a monoid morphism -}</span>
&nbsp;
\ xf -&gt; renderD <span style="color: green;">&#40;</span>xf *% ga<span style="color: green;">&#41;</span> `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` renderD <span style="color: green;">&#40;</span>xf *% gb<span style="color: green;">&#41;</span>
&nbsp;
  == <span style="color: #5d478b; font-style: italic;">{- specification of renderDX  -}</span>
&nbsp;
\ xf -&gt; renderDX ga xf `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` renderDX gb xf
&nbsp;
  == <span style="color: #5d478b; font-style: italic;">{- definition of liftA2/(&lt;*&gt;) on functions -}</span>
&nbsp;
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:liftA2"><span style="font-weight: bold;">liftA2</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a> <span style="color: green;">&#40;</span>renderDX ga<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>renderDX gb<span style="color: green;">&#41;</span>
&nbsp;
  == <span style="color: #5d478b; font-style: italic;">{- definition of mappend on functions -}</span>
&nbsp;
renderDX ga `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` renderDX gb</pre>
</div></p>

<p>Hurray!
<code>renderDX</code> is still a monoid morphism.</p>

<p>The two properties of transformation and union used above say together that <code>(xf *%)</code> is a monoid morphism for all transforms <code>xf</code>.</p>
]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/3d-rendering-as-functional-reactive-programming/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Another angle on functional future values</title>
		<link>http://conal.net/blog/posts/another-angle-on-functional-future-values/</link>
		<comments>http://conal.net/blog/posts/another-angle-on-functional-future-values/#comments</comments>
		<pubDate>Mon, 05 Jan 2009 04:01:05 +0000</pubDate>
		<dc:creator>conal</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[caching]]></category>
		<category><![CDATA[FRP]]></category>
		<category><![CDATA[functional reactive programming]]></category>
		<category><![CDATA[future value]]></category>
		<category><![CDATA[referential transparency]]></category>
		<category><![CDATA[type class morphism]]></category>
		<category><![CDATA[type composition]]></category>

		<guid isPermaLink="false">http://conal.net/blog/?p=73</guid>
		<description><![CDATA[]]></description>
			<content:encoded><![CDATA[<!-- 

Title: Another angle on functional future values

Tags: future value, type class morphism, type composition, caching, referential transparency, FRP, functional reactive programming

URL: http://conal.net/blog/posts/another-angle-on-functional-future-values/

-->

<!-- references -->

<!-- teaser -->

<p>An earlier post introduced functional <em><a href="http://conal.net/blog/posts/future-values/" title="blog post">future values</a></em>, which are values that cannot be known until the future, but can be manipulated in the present.
That post presented a simple denotational semantics of future values simply as time/value pairs.
With a little care in the definition of <code>Time</code> (using the <a href="http://hackage.haskell.org/packages/archive/reactive/latest/doc/html/Data-Max.html" title="module documentation"><code>Max</code> monoid</a>), the instances of <code>Functor</code>, <code>Applicative</code>, <code>Monad</code> are all derived automatically.</p>

<p>A follow-up post gave an implementation of <em><a href="http://conal.net/blog/posts/future-values-via-multi-threading/" title="blog post">Future values via multi threading</a></em>.
Unfortunately, that implementation did not necessarily satisfy the semantics, because it allowed the nondeterminism of thread scheduling to leak through.
Although the implementation is usually correct, I wasn&#8217;t satisfied.</p>

<p>After a while, I hit upon an idea that really tickled me.
My original simple semantics could indeed serve as a correct and workable implementation if I used a subtler form of time that could reveal partial information.
Implementing this subtler form of time turned out to be quite tricky, and was my original motivation for the <code>unamb</code> operator described in the paper <em><a href="http://conal.net/papers/simply-reactive" title="Paper: &quot;Simply efficient functional reactivity&quot;">Simply efficient functional reactivity</a></em> and the post <em><a href="http://conal.net/blog/posts/functional-concurrency-with-unambiguous-choice/" title="blog post">Functional concurrency with unambiguous choice</a></em>.</p>

<p>It took me several days of doodling, pacing outside, and talking to myself before the idea for <code>unamb</code> broke through.
Like many of my favorite ideas, it&#8217;s simple and obvious in retrospect: to remove the ambiguity of nondeterministic choice (as in the <code>amb</code> operator), restrict its use to values that are equal when non-bottom.
Whenever we have two different methods of answering the same question (or possibly failing), we can use <code>unamb</code> to try them both.
Failures (errors or non-termination) are no problem in this context.
A more powerful variation on <code>unamb</code> is the least upper bound operator <code>lub</code>, as described in <em><a href="http://conal.net/blog/posts/merging-partial-values/" title="blog post: &quot;Merging partial values&quot;">Merging partial values</a></em>.</p>

<p>I&#8217;ve been having trouble with the <code>unamb</code> implementation.
When two (compatible) computations race, the loser gets killed so as to free up cycles that are no longer needed.
My first few implementations, however, did not recursively terminate <em>other</em> threads spawned in service of abandoned computations (from nested use of <code>unamb</code>).
I raised this problem in <em><a href="http://conal.net/blog/posts/smarter-termination-for-thread-racing/" title="blog post">Smarter termination for thread racing</a></em>, which suggested some better definitions.
In the course of several helpful reader comments, some problems with my definitions were addressed, particularly in regard to blocking and unblocking exceptions.
None of these definitions so far has done the trick reliably, and now it looks like there is a bug in the GHC run-time system.
I hope the bug (if there is one) will be fixed soon, because I&#8217;m seeing more &amp; more how <code>unamb</code> and <code>lub</code> can make functional programming even more modular (just as laziness does, as explained in <em><a href="http://www.cs.chalmers.se/~rjmh/Papers/whyfp.html" title="Paper by John Hughes">Why Functional Programming Matters</a></em>).</p>

<p>I started playing with future values and unambiguous choice as a way to implement <a href="http://haskell.org/haskellwiki/Reactive" title="Wiki page for the Reactive library">Reactive</a>, a library for functional reactive programming (FRP).
(See <em><a href="http://conal.net/blog/posts/reactive-values-from-the-future/" title="blog post">Reactive values from the future</a></em> and <em><a href="http://conal.net/papers/simply-reactive" title="Paper: &quot;Simply efficient functional reactivity&quot;">Simply efficient functional reactivity</a></em>.)
Over the last few days, I&#8217;ve given some thought to ways to implement future values that don&#8217;t need unambiguous choice.
This post describes one such alternative.</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-73"></span></p>

<h3>Futures, presently</h3>

<p>The current <code>Future</code> type is just a time and a value, wrapped in a a <code>newtype</code>:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">newtype</span> FutureG t a = Future <span style="color: green;">&#40;</span>Time t, a<span style="color: green;">&#41;</span>
  <span style="color: #050; font-weight: bold;">deriving</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="color: #833; font-weight: bold;">Functor</span></a>, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#t:Applicative"><span style="color: #833; font-weight: bold;">Applicative</span></a>, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="color: #833; font-weight: bold;">Monad</span></a><span style="color: green;">&#41;</span></pre>
</div></p>

<p>Where the <code>Time</code> type is defined via the <a href="http://hackage.haskell.org/packages/archive/reactive/latest/doc/html/Data-Max.html" title="module documentation"><code>Max</code> monoid</a>.
The derived instances have exactly the intended meaning for futures, as explained in the post <em><a href="http://conal.net/blog/posts/future-values/" title="blog post">Future values</a></em> and the paper <em><a href="http://conal.net/papers/simply-reactive" title="Paper: &quot;Simply efficient functional reactivity&quot;">Simply efficient functional reactivity</a></em>.
The &#8220;G&#8221; in the name <code>FutureG</code> refers to generalized over time.</p>

<p>Note that <code>Future</code> is parameterized over both time and value.
Originally, I intended this definition as a denotational semantics of future values, but I realized that it could be a workable implementation with a lazy enough <code>t</code>.
In particular, the times have to reveal lower bounds and allow comparisons before they&#8217;re fully known.</p>

<p>Warren Burton explored an applicable notion in the 1980s, which he called &#8220;improving values&#8221;, having a concurrent implementation but deterministic functional semantics.
(See the paper <em><a href="http://journals.cambridge.org/action/displayAbstract?aid=1287720" title="paper by Warren Burton">Encapsulating nondeterminacy in an abstract data type with deterministic semantics</a></em> or the paper <em><a href="http://portal.acm.org/citation.cfm?id=99402" title="paper by Warren Burton">Indeterminate behavior with determinate semantics in parallel programs</a></em>.
I haven&#8217;t found a freely-available online copy of either.)
I adapted Warren&#8217;s idea and gave it an implementation via <code>unamb</code>.</p>

<p>Another operation finds the earlier of two futures.
This operation has an identity and is associative, so I wrapped it up as a <code>Monoid</code> instance:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> t, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bounded"><span style="color: #833; font-weight: bold;">Bounded</span></a> t<span style="color: green;">&#41;</span> =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> <span style="color: green;">&#40;</span>FutureG t a<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a> = Future <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:maxBound"><span style="font-weight: bold;">maxBound</span></a>, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:undefined"><span style="font-weight: bold;">undefined</span></a><span style="color: green;">&#41;</span>
  Future <span style="color: green;">&#40;</span>s,a<span style="color: green;">&#41;</span> `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` Future <span style="color: green;">&#40;</span>t,b<span style="color: green;">&#41;</span> =
    Future <span style="color: green;">&#40;</span>s `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:min"><span style="font-weight: bold;">min</span></a>` t, <span style="color: #050; font-weight: bold;">if</span> s &lt;= t <span style="color: #050; font-weight: bold;">then</span> a <span style="color: #050; font-weight: bold;">else</span> b<span style="color: green;">&#41;</span></pre>
</div></p>

<p>This <code>mappend</code> definition could be written more simply:</p>

<p><div>
<pre class="haskell">  u@<span style="color: green;">&#40;</span>Future <span style="color: green;">&#40;</span>t,_<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` u'@<span style="color: green;">&#40;</span>Future <span style="color: green;">&#40;</span>t',_<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> = <span style="color: #050; font-weight: bold;">if</span> t &lt;= t' <span style="color: #050; font-weight: bold;">then</span> u <span style="color: #050; font-weight: bold;">else</span> u'</pre>
</div></p>

<p>However, the less simple version has more potential for laziness.
The time type might allow yielding partial information about a minimum before both of its arguments are fully known, which is the case with improving values.</p>

<h3>Futures as functions</h3>

<p>The <a href="http://haskell.org/haskellwiki/Reactive" title="Wiki page for the Reactive library">Reactive</a> library uses futures to define and implement reactivity, i.e., behaviors specified piecewise.
Simplifying away the notion of <em>events</em> for now,</p>

<p><div>
<pre class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:until"><span style="font-weight: bold;">until</span></a> :: BehaviorG t a -&gt; FutureG t <span style="color: green;">&#40;</span>BehaviorG t a<span style="color: green;">&#41;</span> -&gt; BehaviorG t a</pre>
</div></p>

<p>The semantics (but not implementation) of <code>BehaviorG</code> is given by</p>

<p><div>
<pre class="haskell">at :: BehaviorG t a -&gt; <span style="color: green;">&#40;</span>t -&gt; a<span style="color: green;">&#41;</span></pre>
</div></p>

<p>The semantics of <code>until</code>:</p>

<p><div>
<pre class="haskell"><span style="color: green;">&#40;</span>b `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:until"><span style="font-weight: bold;">until</span></a>` Future <span style="color: green;">&#40;</span>t',b'<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> `at` t = b'' `at` t
 <span style="color: #050; font-weight: bold;">where</span>
   b'' = <span style="color: #050; font-weight: bold;">if</span> t &lt;= t' <span style="color: #050; font-weight: bold;">then</span> b <span style="color: #050; font-weight: bold;">else</span> b'</pre>
</div></p>

<p>FRP (multi-occurrence) events are then built on top of future values, and reactivity on top of <code>until</code>.</p>

<p>The semantics of <code>until</code> shows what information we need from futures: given a time <code>t</code>, we need to know whether <code>t</code> is later than the future&#8217;s time and, <em>if so</em>, what the future&#8217;s value is.
For other purposes, we&#8217;ll also want to know the future&#8217;s time, but again, only once we&#8217;re past that time.
We might, therefore, represent futures as a function that gives exactly this information.
I&#8217;ll call this function representation &#8220;function futures&#8221; and use the prefix &#8220;S&#8221; to distinguish the original &#8220;simple&#8221; futures from these function futures.</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">type</span> TryFuture t a = Time t -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Maybe"><span style="color: #833; font-weight: bold;">Maybe</span></a> <span style="color: green;">&#40;</span>S.FutureG t a<span style="color: green;">&#41;</span>
&nbsp;
tryFuture :: F.FutureG t a -&gt; TryFuture t a</pre>
</div></p>

<p>Given a probe time, <code>tryFuture</code> gives <code>Nothing</code> if the time is at or before the future&#8217;s time, or <code>Just u</code> otherwise, where <code>u</code> is the simple future.</p>

<p>We could represent <code>F.FutureG</code> simply as <code>TryFuture</code>:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">type</span> F.FutureG = TryFuture  <span style="color: #5d478b; font-style: italic;">-- first try</span></pre>
</div></p>

<p>But then we&#8217;d be stuck with the <code>Functor</code> and <code>Applicative</code> instances for functions instead of futures.
Adding a <code>newtype</code> fixes that problem:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">newtype</span> FutureG t a = Future <span style="color: green;">&#123;</span> unFuture :: FutureGT t a <span style="color: green;">&#125;</span> <span style="color: #5d478b; font-style: italic;">-- second try</span></pre>
</div></p>

<p>With this representation we can easily construct and try out function futures:</p>

<p><div>
<pre class="haskell">future :: TryFuture t a -&gt; FutureG t a
future = Future
&nbsp;
tryFuture :: FutureG t a -&gt; TryFuture t a
tryFuture = unFuture</pre>
</div></p>

<p>I like to define helpers for working inside representations:</p>

<p><div>
<pre class="haskell">inFuture  :: <span style="color: green;">&#40;</span>TryFuture t a -&gt; TryFuture t' a'<span style="color: green;">&#41;</span>
          -&gt; <span style="color: green;">&#40;</span>FutureG   t a -&gt; FutureG   t' a'<span style="color: green;">&#41;</span>
&nbsp;
inFuture2 :: <span style="color: green;">&#40;</span>TryFuture t a -&gt; TryFuture t' a' -&gt; TryFuture t'' a''<span style="color: green;">&#41;</span>
          -&gt; <span style="color: green;">&#40;</span>FutureG   t a -&gt; FutureG   t' a' -&gt; FutureG   t'' a''<span style="color: green;">&#41;</span></pre>
</div></p>

<p>The definitions of these helpers are very simple with the ideas from <em><a href="http://conal.net/blog/posts/prettier-functions-for-wrapping-and-wrapping/" title="blog post">Prettier functions for wrapping and wrapping</a></em> and a lovely notation from Matt Hellige&#8217;s <em><a href="http://matt.immute.net/content/pointless-fun" title="blog post by Matt Hellige">Pointless fun</a></em>.</p>

<p><div>
<pre class="haskell">inFuture  = unFuture ~&gt; Future
&nbsp;
inFuture2 = unFuture ~&gt; inFuture 
&nbsp;
<span style="color: green;">&#40;</span>~&gt;<span style="color: green;">&#41;</span> :: <span style="color: green;">&#40;</span>a' -&gt; a<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>b -&gt; b'<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>a -&gt; b<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>a' -&gt; b'<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
g ~&gt; h = result h . argument g</pre>
</div></p>

<p>These helpers make for some easy definitions in the style of <em><a href="http://conal.net/blog/posts/semantic-editor-combinators/" title="blog post">Semantic editor combinators</a></em>:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="color: #833; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>FutureG t<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> = inFuture.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a>.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a>.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a>
&nbsp;
<span style="color: #050; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bounded"><span style="color: #833; font-weight: bold;">Bounded</span></a> t, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> t<span style="color: green;">&#41;</span> =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#t:Applicative"><span style="color: #833; font-weight: bold;">Applicative</span></a> <span style="color: green;">&#40;</span>FutureG t<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a>  = Future . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a>.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a>.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a>
  <span style="color: green;">&#40;</span>&lt;*&gt;<span style="color: green;">&#41;</span> = <span style="color: green;">&#40;</span>inFuture2.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:liftA2"><span style="font-weight: bold;">liftA2</span></a>.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:liftA2"><span style="font-weight: bold;">liftA2</span></a><span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>&lt;*&gt;<span style="color: green;">&#41;</span></pre>
</div></p>

<h4>Type composition</h4>

<p>These <code>Functor</code> and <code>Applicative</code> instances (for <code>FutureG t</code>) may look mysterious, but they have a common and inevitable form.
Every type whose representation is the (semantic and representational) composition of three functors has this style of <code>Functor</code> instance, and similarly for <code>Applicative</code>.</p>

<p>Instead of repeating this common pattern, let&#8217;s make the type composition explicit, using <a href="http://hackage.haskell.org/packages/archive/TypeCompose/0.6.3/doc/html/Control-Compose.html#2" title="module documentation"><code>Control.Compose</code></a> from the <a href="http://haskell.org/haskellwiki/TypeCompose" title="Wiki page for the TypeCompose library">TypeCompose</a> library:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">type</span> FutureG t = <span style="color: green;">&#40;</span>-&gt;<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>Time t<span style="color: green;">&#41;</span> :. <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Maybe"><span style="color: #833; font-weight: bold;">Maybe</span></a> :. S.FutureG t  <span style="color: #5d478b; font-style: italic;">-- actual definition</span></pre>
</div></p>

<p>Now we can throw out <code>inFuture</code>, <code>inFuture2</code>, <code>(~&gt;)</code>, and the <code>Functor</code> and <code>Applicative</code> instances.
These instances follow from the general instances for type composition.</p>

<h4>Monoid</h4>

<p>The <code>Monoid</code> instance could also come automatically from type composition:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> <span style="color: green;">&#40;</span>g <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>g :. f<span style="color: green;">&#41;</span> a<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <span style="color: green;">&#123;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a> = O <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a> = inO2 <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a> <span style="color: green;">&#125;</span></pre>
</div></p>

<p>The <code>O</code> here is just the <code>newtype</code> constructor for <code>(:.)</code>, and the <code>inO2</code> function is similar to <code>inFuture2</code> above.</p>

<p>However, there is another often-useful <code>Monoid</code> instance:</p>

<p><div>
<pre class="haskell"><span style="color: #5d478b; font-style: italic;">-- standard Monoid instance for Applicative applied to Monoid</span>
<span style="color: #050; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#t:Applicative"><span style="color: #833; font-weight: bold;">Applicative</span></a> <span style="color: green;">&#40;</span>g :. f<span style="color: green;">&#41;</span>, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> a<span style="color: green;">&#41;</span> =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>g :. f<span style="color: green;">&#41;</span> a<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <span style="color: green;">&#123;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:liftA2"><span style="font-weight: bold;">liftA2</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a> <span style="color: green;">&#125;</span></pre>
</div></p>

<p>Because these two instances &#8220;overlap&#8221; are are both useful, neither one is declared in the general case.
Instead, specialized instances are declared where needed, e.g.,</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> t, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bounded"><span style="color: #833; font-weight: bold;">Bounded</span></a> t<span style="color: green;">&#41;</span> =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> <span style="color: green;">&#40;</span>FutureG t a<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>  = <span style="color: green;">&#40;</span>  O .  O <span style="color: green;">&#41;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>   <span style="color: #5d478b; font-style: italic;">-- or future mempty</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a> = <span style="color: green;">&#40;</span>inO2.inO2<span style="color: green;">&#41;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a></pre>
</div></p>

<p>How does the <code>Monoid</code> instance work?  Start with <code>mempty</code>.  Expanding:</p>

<p><div>
<pre class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>
&nbsp;
  == <span style="color: #5d478b; font-style: italic;">{- definition -}</span> 
&nbsp;
O <span style="color: green;">&#40;</span>O <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a><span style="color: green;">&#41;</span>
&nbsp;
  == <span style="color: #5d478b; font-style: italic;">{- mempty on functions -}</span>
&nbsp;
O <span style="color: green;">&#40;</span>O <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
  == <span style="color: #5d478b; font-style: italic;">{- mempty on Maybe -}</span>
&nbsp;
O <span style="color: green;">&#40;</span>O <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a> Nothing<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre>
</div></p>

<p>So, given any probe time, the empty (never-occurring) future says that it does not occur before the probe time.</p>

<p>Next, <code>mappend</code>:</p>

<p><div>
<pre class="haskell">O <span style="color: green;">&#40;</span>O f<span style="color: green;">&#41;</span> `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` O <span style="color: green;">&#40;</span>O f'<span style="color: green;">&#41;</span>
&nbsp;
  == <span style="color: #5d478b; font-style: italic;">{- mappend on FutureG -}</span>
&nbsp;
O <span style="color: green;">&#40;</span>O <span style="color: green;">&#40;</span>f `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` f'<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
  == <span style="color: #5d478b; font-style: italic;">{- mappend on functions -}</span>
&nbsp;
O <span style="color: green;">&#40;</span>O <span style="color: green;">&#40;</span>\ t -&gt; f t `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` f' t<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
  == <span style="color: #5d478b; font-style: italic;">{- mappend on Maybe -}</span>
&nbsp;
O <span style="color: green;">&#40;</span>O <span style="color: green;">&#40;</span>\ t -&gt; f t `mappendMb` f' t<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
  <span style="color: #050; font-weight: bold;">where</span>
    Nothing `mappendMb` mb'    = mb'
    mb `mappendMb` Nothing     = mb
    Just u `mappendMb` Just u' = Just <span style="color: green;">&#40;</span>u `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` u'<span style="color: green;">&#41;</span></pre>
</div></p>

<p>The <code>mappend</code> in this last line is on simple futures, as defined above, examining the (now known) times and choosing the earlier future.
Previously, I took special care in that <code>mappend</code> definition to enable <code>min</code> to produce information before knowing whether <code>t &lt;= t'</code>.
However, with this new approach to futures, I expect to use simple (flat) times, so it could instead be</p>

<p><div>
<pre class="haskell">u@<span style="color: green;">&#40;</span>Future <span style="color: green;">&#40;</span>s,_<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` u'@<span style="color: green;">&#40;</span>Future <span style="color: green;">&#40;</span>s',_<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> = <span style="color: #050; font-weight: bold;">if</span> s &lt;= s' <span style="color: #050; font-weight: bold;">then</span> u <span style="color: #050; font-weight: bold;">else</span> u'</pre>
</div></p>

<p>or</p>

<p><div>
<pre class="haskell">u `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` u' = <span style="color: #050; font-weight: bold;">if</span> futTime u &lt;= futTime u' <span style="color: #050; font-weight: bold;">then</span> u <span style="color: #050; font-weight: bold;">else</span> u'
&nbsp;
futTime <span style="color: green;">&#40;</span>Future <span style="color: green;">&#40;</span>t,_<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> = t</pre>
</div></p>

<p>or</p>

<p><div>
<pre class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a> = minBy futTime</pre>
</div></p>

<p>How does <code>mappend</code> work on function futures?
Given a test time <code>t</code>, if both futures are at least <code>t</code>, then the combined future is at least <code>t</code> (yielding <code>Nothing</code>).
If either future is before <code>t</code> and the other isn&#8217;t, then the combined future is the same as the one before <code>t</code>.
If both futures are before <code>t</code>, then the combined future is the earlier one.</p>

<h4>Relating function futures and simple futures</h4>

<p>The function-based representation of futures relates closely to the simple representation.
Let&#8217;s make this relationship explcit by defining mappings between them:</p>

<p><div>
<pre class="haskell">sToF :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> t =&gt; S.FutureG t a -&gt; F.FutureG t a
&nbsp;
fToS :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> t =&gt; F.FutureG t a -&gt; S.FutureG t a</pre>
</div></p>

<p>The first one is easy:</p>

<p><div>
<pre class="haskell">sToF u@<span style="color: green;">&#40;</span>S.Future <span style="color: green;">&#40;</span>t, _<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> =
  future <span style="color: green;">&#40;</span>\ t' -&gt; <span style="color: #050; font-weight: bold;">if</span> t' &lt;= t <span style="color: #050; font-weight: bold;">then</span> Nothing <span style="color: #050; font-weight: bold;">else</span> Just u<span style="color: green;">&#41;</span></pre>
</div></p>

<p>The reverse mapping, <code>fToS</code>, is trickier and is only defined on the image (codomain) of <code>sToF</code>.
I think it can be defined mathematically but not computationally.
There are two cases: either the function always returns <code>Nothing</code>, or there is at least one <code>t</code> for which it returns a <code>Just</code>.
If the former, then the simple future is <code>mempty</code>, which is <code>S.Future (maxBound, undefined)</code>.
If the latter, then there is only one such <code>Just</code>, and the simple future is the one in that <code>Just</code>.
Together, <code>(sToF, fToS)</code> form a projection-embedding pair.</p>

<p>We won&#8217;t really have to implement or invoke these functions.
Instead, they serve to further specify the type <code>F.FutureG</code> and the correctness of operations on it.
The representation of <code>F.FutureG</code> as given allows many values that do not correspond to futures.
To eliminate these representations, require an invariant that a function future must be the result of applying <code>sToF</code> to some simple future.</p>

<p>We&#8217;ll require that each operation preserves this invariant.
However, let&#8217;s prove something stronger, namely that operations on on <code>F.FutureG</code> correspond precisely to the same operations on <code>S.FutureG</code>, via <code>sToF</code>.
In other words, <code>sToF</code> preserves the shape of the operations on futures.
For type classes, these correspondences are the type class morphisms.
For instance, <code>sToF</code> is a <code>Monoid</code> morphism:</p>

<p><div>
<pre class="haskell">sToF <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a> == <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>
&nbsp;
sToF <span style="color: green;">&#40;</span>u `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` u'<span style="color: green;">&#41;</span> == sToF u `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` sToF u'</pre>
</div></p>

<h3>Caching futures</h3>

<p>This function representation eliminates the need for tricky times (using improving values and <code>unamb</code>), but it loses the caching benefit that lazy functional programming affords to non-function representations.
Now let&#8217;s reclaim that benefit.
The trick is to exploit the restriction that every function future must be 
(semantically) the image of a simple future under <code>sToF</code>.</p>

<p>Examining the definition of <code>sToF</code>, we can deduce the following monotonicity properties of (legitimate) function futures:</p>

<ul>
<li>If the probe function yields <code>Nothing</code> for some <code>t'</code>, then it yields <code>Nothing</code> for earlier times.</li>
<li>If the probe function yields <code>Just u</code> for some <code>t'</code>, then it yields <code>Just u</code> for all later times.</li>
</ul>

<p>We can exploit these monotonicity properties by caching information as we learn it.
Caching of this sort is what distinguishes call-by-need from call-by-name and allows lazy evaluation to work efficiently for data representations.</p>

<p>Specifically, let&#8217;s save a best-known lower bound for the future time and the simple future when known.
Since the lower bound may get modified a few times, I&#8217;ll use a <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Concurrent-SampleVar.html#v:SampleVar"><code>SampleVar</code></a> (thread-safe rewritable variable).
The simple future will be discovered only once, so I&#8217;ll use an <a href="http://hackage.haskell.org/packages/archive/reactive/latest/doc/html/FRP-Reactive-Internal-IVar.html"><code>IVar</code></a>.
I&#8217;ll keep the function-future for probing when the cached information is not sufficient to answer a query.</p>

<p>Prefix this caching version with a &#8220;C&#8221;, to distinguish it from function futures (&#8220;F&#8221;) and the simple futures (&#8220;S&#8221;):</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">data</span> C.FutureG t a =
  Future <span style="color: green;">&#40;</span>SampleVar t<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>IVar <span style="color: green;">&#40;</span>S.FutureG t a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>F.FutureG t a<span style="color: green;">&#41;</span></pre>
</div></p>

<p>Either the simple future or the function future will be useful, so we could replace the second two fields with a single one:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">data</span> C.FutureG t a =
  Future <span style="color: green;">&#40;</span>SampleVar t<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>MVar <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="color: #833; font-weight: bold;">Either</span></a> <span style="color: green;">&#40;</span>F.FutureG t a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>FF.FutureG t a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre>
</div></p>

<p>We&#8217;ll have to be careful about multiple independent discoveries of the same simple future, which would correspond to multiple writes <code>IVar</code> with the same value.
(I imagine there are related mechanics in the GHC RTS for two threads evaluating the same thunk that would be helpful to understand.)
I guess I could use a <code>SampleVar</code> and just not worry about multiple writes, since they&#8217;d be equivalent.
For now, use the <code>IVar</code> version.</p>

<p>The caching representation relates to the function representation by means of two functions:</p>

<p><div>
<pre class="haskell">dToF :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a>     t =&gt; C.FutureG t a -&gt; F.FutureG t a
&nbsp;
fToD :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bounded"><span style="color: #833; font-weight: bold;">Bounded</span></a> t =&gt; F.FutureG t a -&gt; C.FutureG t a</pre>
</div></p>

<p>The implementation</p>

<p><div>
<pre class="haskell">dToF <span style="color: green;">&#40;</span>C.Future tv uv uf<span style="color: green;">&#41;</span> =
  F.Future $ \ t' -&gt; unsafePerformIO $
    <span style="color: #050; font-weight: bold;">do</span> mb &lt;- tryReadIVar uv
       <span style="color: #050; font-weight: bold;">case</span> mb <span style="color: #050; font-weight: bold;">of</span>
         j@<span style="color: green;">&#40;</span>Just <span style="color: green;">&#40;</span>S.Future <span style="color: green;">&#40;</span>Max t,_<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> -&gt;
           <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> <span style="color: green;">&#40;</span><span style="color: #050; font-weight: bold;">if</span> t' &lt;= t <span style="color: #050; font-weight: bold;">then</span> Nothing <span style="color: #050; font-weight: bold;">else</span> j<span style="color: green;">&#41;</span>
         Nothing        -&gt;
           <span style="color: #050; font-weight: bold;">do</span> tlo &lt;- readSampleVar tv
              <span style="color: #050; font-weight: bold;">if</span> t' &lt;= tlo <span style="color: #050; font-weight: bold;">then</span>
                 <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> Nothing
               <span style="color: #050; font-weight: bold;">else</span>
                 <span style="color: #050; font-weight: bold;">do</span> <span style="color: #050; font-weight: bold;">let</span> mb' = F.unFuture uf t'
                    writeIVarMaybe uv mb'
                    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> mb'
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- Perhaps write to an IVar</span>
writeIVarMaybe :: IVar a -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Maybe"><span style="color: #833; font-weight: bold;">Maybe</span></a> a -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:IO"><span style="color: #833; font-weight: bold;">IO</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
writeIVarMaybe v = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:maybe"><span style="font-weight: bold;">maybe</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>writeIVar v<span style="color: green;">&#41;</span>
&nbsp;
fToD uf = unsafePerformIO $
          <span style="color: #050; font-weight: bold;">do</span> tv &lt;- newSampleVar t0
             uv &lt;- newIVar
             writeIVarMaybe uv <span style="color: green;">&#40;</span>F.unFuture uf t0<span style="color: green;">&#41;</span>
             <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> <span style="color: green;">&#40;</span>Future tv uv uf<span style="color: green;">&#41;</span>
 <span style="color: #050; font-weight: bold;">where</span>
   t0 = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:minBound"><span style="font-weight: bold;">minBound</span></a></pre>
</div></p>

<p>It&#8217;ll be handy to delegate operations to <code>F.Future</code>:</p>

<p><div>
<pre class="haskell">inF :: <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> t, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bounded"><span style="color: #833; font-weight: bold;">Bounded</span></a> t'<span style="color: green;">&#41;</span> =&gt;
       <span style="color: green;">&#40;</span>F.FutureG t a -&gt; F.FutureG t' a'<span style="color: green;">&#41;</span>
    -&gt; <span style="color: green;">&#40;</span>  FutureG t a -&gt;   FutureG t' a'<span style="color: green;">&#41;</span>
inF = dToF ~&gt; fToD
&nbsp;
inF2 :: <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> t, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bounded"><span style="color: #833; font-weight: bold;">Bounded</span></a> t', <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> t', <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bounded"><span style="color: #833; font-weight: bold;">Bounded</span></a> t''<span style="color: green;">&#41;</span> =&gt;
        <span style="color: green;">&#40;</span>F.FutureG t a -&gt; F.FutureG t' a' -&gt; F.FutureG t'' a''<span style="color: green;">&#41;</span>
     -&gt; <span style="color: green;">&#40;</span>  FutureG t a -&gt;   FutureG t' a' -&gt;   FutureG t'' a''<span style="color: green;">&#41;</span>
inF2 = dToF ~&gt; inF</pre>
</div></p>

<p>Then</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> t, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bounded"><span style="color: #833; font-weight: bold;">Bounded</span></a> t<span style="color: green;">&#41;</span> =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> <span style="color: green;">&#40;</span>FutureG t a<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>  = fToD <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a> = inF2 <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>
&nbsp;
<span style="color: #050; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> t, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bounded"><span style="color: #833; font-weight: bold;">Bounded</span></a> t<span style="color: green;">&#41;</span> =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="color: #833; font-weight: bold;">Functor</span></a>     <span style="color: green;">&#40;</span>FutureG t<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> = inF . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a>
&nbsp;
<span style="color: #050; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> t, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bounded"><span style="color: #833; font-weight: bold;">Bounded</span></a> t<span style="color: green;">&#41;</span> =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#t:Applicative"><span style="color: #833; font-weight: bold;">Applicative</span></a> <span style="color: green;">&#40;</span>FutureG t<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a>  = fToD . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a>
  <span style="color: green;">&#40;</span>&lt;*&gt;<span style="color: green;">&#41;</span> = inF2 <span style="color: green;">&#40;</span>&lt;*&gt;<span style="color: green;">&#41;</span></pre>
</div></p>

<h3>Wrap-up</h3>

<p>Well, that&#8217;s the idea.
I&#8217;ve gotten as far as type-checking the code in this post, but I haven&#8217;t yet tried running it.</p>

<p>What interests me most above is the use of <code>unsafePerformIO</code> here while preserving referential transparency, thanks to the invariant on <code>F.FutureG</code> (and the consequent monotonicity property).
The heart of lazy evaluation of <em>pure</em> functional programs is just such an update, replacing a thunk with its weak head normal form (whnf).
What general principles can we construct that allow us to use efficient, destructive updating and still have referential transparency?
The important thing above seems to be the careful definition of an abstract interface such that the effect of state updates is semantically invisible through the interface.</p>
]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/another-angle-on-functional-future-values/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Functional interactive behavior</title>
		<link>http://conal.net/blog/posts/functional-interactive-behavior/</link>
		<comments>http://conal.net/blog/posts/functional-interactive-behavior/#comments</comments>
		<pubDate>Wed, 10 Dec 2008 09:26:50 +0000</pubDate>
		<dc:creator>conal</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[comonad]]></category>
		<category><![CDATA[FRP]]></category>
		<category><![CDATA[functional reactive programming]]></category>
		<category><![CDATA[interaction]]></category>

		<guid isPermaLink="false">http://conal.net/blog/?p=70</guid>
		<description><![CDATA[]]></description>
			<content:encoded><![CDATA[<!-- 

Title: Functional interactive behavior

Tags: FRP, functional reactive programming, interaction

URL: http://conal.net/blog/posts/functional-interactive-behavior/

-->

<!-- references -->

<!-- teaser -->

<p>In a previous post, I presented a fundamental reason <em><a href="http://conal.net/blog/posts/why-classic-FRP-does-not-fit-interactive-behavior/" title="blog post">why classic FRP does not fit interactive behavior</a></em>, which is that the semantic model captures only the influence of time and not other input.
I also gave a simple alternative, with a simple and general model for temporal and spatial transformation, in which input behavior is transformed inversely to the transformation of output behavior.</p>

<p>The semantic model I suggested is the same as used in &#8220;Arrow FRP&#8221;, from <a href="http://conal.net/papers/genuinely-functional-guis.pdf" title="Paper: &quot;Genuinely Functional User Interfaces&quot;">Fruit</a> and <a href="http://haskell.org/haskellwiki/Yampa" title="Wiki page">Yampa</a>.
I want, however, a more convenient and efficient way to package up that model, which is the subject of the post you are reading now.</p>

<p>Next, we took a close look at one awkward aspect of classic FRP for interactive behavior, namely the need to <a href="http://conal.net/blog/posts/trimming-inputs-in-functional-reactive-programming/" title="blog post">trim inputs</a>, and how trimming relates to <a href="http://conal.net/blog/tag/comonad/">comonadic</a> FRP.
The <code>trim</code> function allows us to define multi-phase interactive behaviors correctly and efficiently, but its use is tedious and is easy to get wrong.
It thus fails to achieve what I want from functional programming in general and FRP in particular, which is to enable writing simple, natural descriptions, free of mechanical details.</p>

<p>The current post hides and automates the mechanics of trimming, so that the intent of an interactive behavior can be expressed directly and executed correctly and efficiently.</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-70"></span></p>

<p>As before, I&#8217;ll adopt two abbreviations, for succinctness:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">type</span> B = Behavior
<span style="color: #050; font-weight: bold;">type</span> E = Event</pre>
</div></p>

<h3>Safe and easy trimming</h3>

<p><a href="http://conal.net/blog/posts/trimming-inputs-in-functional-reactive-programming/" title="blog post">Previously</a>, I defined an interactive cat behavior as follows:</p>

<p><div>
<pre class="haskell">cat3 :: B World -&gt; B Cat
cat3 world = sleep world `switcher`
               <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:uncurry"><span style="font-weight: bold;">uncurry</span></a> prowl &lt;$&gt; trimf wake   world<span style="color: green;">&#41;</span> `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>`
                <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:uncurry"><span style="font-weight: bold;">uncurry</span></a> eat   &lt;$&gt; trimf hunger world<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre>
</div></p>

<p>I&#8217;d really like to write the following</p>

<p><div>
<pre class="haskell"><span style="color: #5d478b; font-style: italic;">-- ideal:</span>
cat4 = sleep `switcher` <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>prowl &lt;$&gt; wake<span style="color: green;">&#41;</span> `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` <span style="color: green;">&#40;</span>eat &lt;$&gt; hunger<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre>
</div></p>

<p>Let&#8217;s see how close we can get.</p>

<p>I can see right off I&#8217;ll have to replace or generalize <code>switcher</code>.
For now, I&#8217;ll replace it:</p>

<p><div>
<pre class="haskell">switcherf :: <span style="color: green;">&#40;</span>B i -&gt; B o<span style="color: green;">&#41;</span>
          -&gt; <span style="color: green;">&#40;</span>B i -&gt; E <span style="color: green;">&#40;</span>B i -&gt; B o<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
          -&gt; <span style="color: green;">&#40;</span>B i -&gt; B o<span style="color: green;">&#41;</span></pre>
</div></p>

<p>This function will have to manage trimming:</p>

<p><div>
<pre class="haskell">bf `switcherf` ef = \ i -&gt;
  bf i `switcher` <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:uncurry"><span style="font-weight: bold;">uncurry</span></a> <span style="color: green;">&#40;</span>$<span style="color: green;">&#41;</span> &lt;$&gt; trimf ef i<span style="color: green;">&#41;</span></pre>
</div></p>

<p>I won&#8217;t have to replace <code>mappend</code>, since it&#8217;s a method and so can have a variety of types.
In this case, <code>mappend</code> applies to a function from behaviors to events.
Fortunately, the function monoid is exactly what we need:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> b =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> <span style="color: green;">&#40;</span>a -&gt; b<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>        = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>
  f `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` g = \ a -&gt; f a `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` f b</pre>
</div></p>

<p>or the more lovely standard form for applicative functors:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> b =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> <span style="color: green;">&#40;</span>a -&gt; b<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>  = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a>   <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:liftA2"><span style="font-weight: bold;">liftA2</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a></pre>
</div></p>

<p>The use of <code>(&lt;$&gt;)</code> (i.e., <code>fmap</code>) in <code>cat4</code> above won&#8217;t work.
We want instead to <code>fmap</code> inside the <em>result</em> of a function from behaviors to events.
Using the style of <a href="http://conal.net/blog/posts/semantic-editor-combinators/" title="blog post">semantic editor combinators</a>, we get the following definition, which is fairly close to our ideal:</p>

<p><div>
<pre class="haskell">cat4 = sleep `switcherf`
         <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>result.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a><span style="color: green;">&#41;</span> prowl wake `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` <span style="color: green;">&#40;</span>result.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a><span style="color: green;">&#41;</span> eat hunger<span style="color: green;">&#41;</span></pre>
</div></p>

<h3>Generalized switching</h3>

<p>To generalize <code>switcher</code>, introduce a new type class:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">class</span> Switchable b e <span style="color: #050; font-weight: bold;">where</span> switcher :: b -&gt; e b -&gt; b</pre>
</div></p>

<p>The original Reactive <code>switcher</code> is a special case:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> Switchable <span style="color: green;">&#40;</span>B a<span style="color: green;">&#41;</span> E <span style="color: #050; font-weight: bold;">where</span> switcher = R.switcher</pre>
</div></p>

<p>We can switch among tuples and among other containers of switchables.
For instance,</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="color: #833; font-weight: bold;">Functor</span></a> e, Switchable b e, Switchable b' e<span style="color: green;">&#41;</span>
      =&gt; Switchable <span style="color: green;">&#40;</span>b,b'<span style="color: green;">&#41;</span> e <span style="color: #050; font-weight: bold;">where</span>
  <span style="color: green;">&#40;</span>b,b'<span style="color: green;">&#41;</span> `switcher` e = <span style="color: green;">&#40;</span> b  `switcher` <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fst"><span style="font-weight: bold;">fst</span></a> &lt;$&gt; e<span style="color: green;">&#41;</span>
                        , b' `switcher` <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:snd"><span style="font-weight: bold;">snd</span></a> &lt;$&gt; e<span style="color: green;">&#41;</span> <span style="color: green;">&#41;</span></pre>
</div></p>

<h3>Temporal values</h3>

<p>Looking through the examples above, all we really had to do with the input behavior was to compute all remainders.
I used</p>

<p><div>
<pre class="haskell">duplicate :: B a -&gt; B <span style="color: green;">&#40;</span>B a<span style="color: green;">&#41;</span></pre>
</div></p>

<p>More generally,</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">class</span> Temporal a <span style="color: #050; font-weight: bold;">where</span> remainders :: a -&gt; B a</pre>
</div></p>

<p>Behaviors and events are included as a special case,</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> Temporal <span style="color: green;">&#40;</span>B a<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span> remainders = duplicate
&nbsp;
<span style="color: #050; font-weight: bold;">instance</span> Temporal <span style="color: green;">&#40;</span>E a<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span> remainders = ...</pre>
</div></p>

<p>Temporal values combine without losing their individuality, which allows efficient change-driven evaluation as in <em><a href="http://conal.net/blog/posts/simply-efficient-functional-reactivity/" title="blog post">Simply efficient functional reactivity</a></em>:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span>Temporal a, Temporal b<span style="color: green;">&#41;</span> =&gt; Temporal <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  remainders <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> = remainders a `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:zip"><span style="font-weight: bold;">zip</span></a>` remainders b</pre>
</div></p>

<p>Similarly for other triples and other data structures.</p>

<p>Sometimes it&#8217;s handy to carry static information along with dynamic information.
Static types can be made trivially temporal:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> Temporal <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="color: #833; font-weight: bold;">Bool</span></a> <span style="color: #050; font-weight: bold;">where</span> remainders = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a>
<span style="color: #050; font-weight: bold;">instance</span> Temporal <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #833; font-weight: bold;">Int</span></a>  <span style="color: #050; font-weight: bold;">where</span> remainders = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a>
<span style="color: #5d478b; font-style: italic;">-- etc</span></pre>
</div></p>

<p>With this <code>Temporal</code> class, the trimming definitions above have more general types.</p>

<p><div>
<pre class="haskell">trim  :: Temporal i =&gt; E o -&gt; i -&gt; E <span style="color: green;">&#40;</span>o, i<span style="color: green;">&#41;</span>
&nbsp;
trimf :: Temporal i =&gt; <span style="color: green;">&#40;</span>i -&gt; E o<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>i -&gt; E <span style="color: green;">&#40;</span>o, i<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre>
</div></p>

<p>As does function switching:</p>

<p><div>
<pre class="haskell">switcherf :: <span style="color: green;">&#40;</span>Temporal i, Switchable o E<span style="color: green;">&#41;</span> =&gt;
             <span style="color: green;">&#40;</span>i -&gt; o<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>i -&gt; E <span style="color: green;">&#40;</span>i -&gt; o<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> -&gt; i -&gt; o</pre>
</div></p>

<h3>Types for functional interactive behavior</h3>

<p>We&#8217;ve gotten almost to my ideal cat definition.
We cannot, however, use <code>switcher</code> or <code>(&lt;$&gt;)</code> here with functions from behaviors to behaviors, because the types don&#8217;t fit.</p>

<p>To cross the last gap, let&#8217;s define new types corresponding to the idioms we&#8217;ve seen repeatedly above.</p>

<p><div>
<pre class="haskell"><span style="color: #5d478b; font-style: italic;">-- First try</span>
<span style="color: #050; font-weight: bold;">type</span> i :~&gt; o = BI <span style="color: green;">&#40;</span>B i -&gt; B o<span style="color: green;">&#41;</span>
<span style="color: #050; font-weight: bold;">type</span> i :-&gt; o = EI <span style="color: green;">&#40;</span>B i -&gt; E o<span style="color: green;">&#41;</span></pre>
</div></p>

<p>Or, using <a href="http://haskell.org/haskellwiki/TypeCompose" title="Wiki page">type composition</a>:</p>

<p><div>
<pre class="haskell"><span style="color: #5d478b; font-style: italic;">-- Second try</span>
<span style="color: #050; font-weight: bold;">type</span> <span style="color: green;">&#40;</span>:~&gt;<span style="color: green;">&#41;</span> i = <span style="color: green;">&#40;</span>-&gt;<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>B i<span style="color: green;">&#41;</span> :. B
<span style="color: #050; font-weight: bold;">type</span> <span style="color: green;">&#40;</span>:-&gt;<span style="color: green;">&#41;</span> i = <span style="color: green;">&#40;</span>-&gt;<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>B i<span style="color: green;">&#41;</span> :. E</pre>
</div></p>

<p>The advantage of type composition is that we get some useful definitions for free, including <code>Functor</code> and <code>Applicative</code> instances.</p>

<p>However, there&#8217;s a problem with both versions.
They limit us to a single behavior as input.
A realistic interactive environment has many inputs, including a mixture of behaviors and events.</p>

<p>In Yampa, that mixture is combined into a single behavior, leading to two difficulties:</p>

<ul>
<li>The distinction between behaviors and events gets lost, as well as (I think) accurate and minimal-latency event detection and response.</li>
<li>The bundled input environment changes whenever any component changes, leading to everything getting recomputed and redisplayed when anything changes.</li>
</ul>

<p>To avoid these problems, I&#8217;ll take a different approach.
Generalize inputs from behaviors to arbitrary <code>Temporal</code> values, which include behaviors, events and tuples and structures of temporal values.</p>

<p>The types for interactive behaviors and interactive events are</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">type</span> <span style="color: green;">&#40;</span>:~&gt;<span style="color: green;">&#41;</span> i = <span style="color: green;">&#40;</span>-&gt;<span style="color: green;">&#41;</span> i :. B
<span style="color: #050; font-weight: bold;">type</span> <span style="color: green;">&#40;</span>:-&gt;<span style="color: green;">&#41;</span> i = <span style="color: green;">&#40;</span>-&gt;<span style="color: green;">&#41;</span> i :. E</pre>
</div></p>

<p>So <code>i :~&gt; o</code> is like <code>i -&gt; B o</code>, and <code>i :-&gt; o</code> is like <code>i -&gt; E o</code>.</p>

<p>Switching for interactive behaviors wraps the <code>switcherf</code> function from above:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> Temporal i =&gt; Switchable <span style="color: green;">&#40;</span>i :~&gt; o<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>:-&gt;<span style="color: green;">&#41;</span> i<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  switcher = inO2 $ \ bf ef -&gt; bf `switcherf` <span style="color: green;">&#40;</span>result.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a><span style="color: green;">&#41;</span> unO ef</pre>
</div></p>

<p>The <code>inO2</code> and <code>unO</code> functions from <a href="http://haskell.org/haskellwiki/TypeCompose" title="Wiki page">TypeCompose</a> just manipulate <code>newtype</code> wrappers.
See <em><a href="http://conal.net/blog/posts/prettier-functions-for-wrapping-and-wrapping/" title="blog post">Prettier functions for wrapping and wrapping</a></em>.</p>

<p>This definition is actually more general than the type given here.
For instance, it can be used to switch between interactive <em>events</em> as well as interactive <em>behaviors</em>.
To see the generalization, first abstract out the commonality between <code>(:~&gt;)</code> and <code>(:-&gt;)</code>:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">type</span> i :-&gt;. f = <span style="color: green;">&#40;</span>-&gt;<span style="color: green;">&#41;</span> i :. f
&nbsp;
<span style="color: #050; font-weight: bold;">type</span> <span style="color: green;">&#40;</span>:~&gt;<span style="color: green;">&#41;</span> i = i :-&gt;. B
<span style="color: #050; font-weight: bold;">type</span> <span style="color: green;">&#40;</span>:-&gt;<span style="color: green;">&#41;</span> i = i :-&gt;. E</pre>
</div></p>

<p>The same instance code but with a more general type:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span>Temporal i, Switchable <span style="color: green;">&#40;</span>f o<span style="color: green;">&#41;</span> E<span style="color: green;">&#41;</span>
      =&gt; Switchable <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>i :-&gt;. f<span style="color: green;">&#41;</span> o<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>:-&gt;<span style="color: green;">&#41;</span> i<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  switcher = inO2 $ \ bf ef -&gt; bf `switcherf` <span style="color: green;">&#40;</span>result.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a><span style="color: green;">&#41;</span> unO ef</pre>
</div></p>

<p>We can also switch between interactive <em>collections</em> of behaviors and events, though not with the <code>(:-&gt;.)</code> wrapping.</p>

<h3>Where are we?</h3>

<p>Almost all of the pieces are in place now.
Another post will relate input trimming to the time transformation of interactive behaviors, as discussed in 
<em><a href="http://conal.net/blog/posts/why-classic-FRP-does-not-fit-interactive-behavior/" title="blog post">Why classic FRP does not fit interactive behavior</a></em>.
Also, how interactive FRP relates to <em><a href="http://conal.net/blog/posts/sequences-segments-and-signals/" title="blog post">Sequences, segments, and signals</a></em>.</p>
]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/functional-interactive-behavior/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Trimming inputs in functional reactive programming</title>
		<link>http://conal.net/blog/posts/trimming-inputs-in-functional-reactive-programming/</link>
		<comments>http://conal.net/blog/posts/trimming-inputs-in-functional-reactive-programming/#comments</comments>
		<pubDate>Wed, 10 Dec 2008 09:00:33 +0000</pubDate>
		<dc:creator>conal</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[comonad]]></category>
		<category><![CDATA[FRP]]></category>
		<category><![CDATA[functional reactive programming]]></category>
		<category><![CDATA[interaction]]></category>

		<guid isPermaLink="false">http://conal.net/blog/?p=71</guid>
		<description><![CDATA[]]></description>
			<content:encoded><![CDATA[<!-- 

Title: Trimming inputs in functional reactive programming

Tags: FRP, functional reactive programming, interaction, comonad

URL: http://conal.net/blog/posts/trimming-inputs-in-functional-reactive-programming/

-->

<!-- references -->

<!-- teaser -->

<p>This post takes a close look at one awkward aspect of <em>classic</em> (non-arrow) FRP for interactive behavior, namely the need to <em>trim</em> (or &#8220;age&#8221;) old input.
Failing to trim results in behavior that is incorrect and grossly inefficient.</p>

<p>Behavior trimming connects directly into the <a href="http://conal.net/blog/tag/comonad/">comonad</a> interface mentioned in a few recent posts, and is what got me interested in comonads recently.</p>

<p>In absolute-time FRP, trimming has a purely operational significance.
Switching to relative time, trimming is recast as a semantically familiar operation, namely the generalized <code>drop</code> function used in two <a href="http://conal.net/blog/tag/segment/">recent posts</a>.</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-71"></span></p>

<p>In the rest of this post, I&#8217;ll adopt two abbreviations, for succinctness:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">type</span> B = Behavior
<span style="color: #050; font-weight: bold;">type</span> E = Event</pre>
</div></p>

<h3>Trimming inputs</h3>

<p>An awkward aspect of classic FRP has to do with switching phases of behavior.
Each phase is a function of some static (momentary) input and some dynamic (time-varying) input, e.g.,</p>

<p><div>
<pre class="haskell">sleep :: B World -&gt; B Cat
eat   :: Appetite   -&gt; B World -&gt; B Cat
prowl :: Friskiness -&gt; B World -&gt; B Cat
&nbsp;
wake   :: B World -&gt; E Friskiness
hunger :: B World -&gt; E Appetite</pre>
</div></p>

<p>As a first try, our cat prowls upon waking and eats when hungry, taking into account its surrounding world:</p>

<p><div>
<pre class="haskell">cat1 :: B World -&gt; B Cat
cat1 world = sleep world `switcher`
               <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:flip"><span style="font-weight: bold;">flip</span></a> prowl world &lt;$&gt; wake   world<span style="color: green;">&#41;</span> `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>`
                <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:flip"><span style="font-weight: bold;">flip</span></a> eat   world &lt;$&gt; hunger world<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre>
</div></p>

<p>The <code>(&lt;$&gt;)</code> here, from <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html" title="Haskell module documentation">Control.Applicative</a>, is a synonym for <code>fmap</code>.
In this context,</p>

<p><div>
<pre class="haskell"><span style="color: green;">&#40;</span>&lt;$&gt;<span style="color: green;">&#41;</span> :: <span style="color: green;">&#40;</span>a -&gt; B Cat<span style="color: green;">&#41;</span> -&gt; E a -&gt; E <span style="color: green;">&#40;</span>B Cat<span style="color: green;">&#41;</span></pre>
</div></p>

<p>The FRP <code>switcher</code> function switches to new behavior phases as they&#8217;re generated by an event, beginning with a given initial behavior:</p>

<p><div>
<pre class="haskell">switcher :: B a -&gt; E <span style="color: green;">&#40;</span>B a<span style="color: green;">&#41;</span> -&gt; B a</pre>
</div></p>

<p>And the <code>mappend</code> here merges two events into one, combining their occurrences.</p>

<p>When switching phases, we generally want the new phase to start responding to input exactly where the old phase left off.
If we&#8217;re not careful, however, the new phase will begin with an old input.
I&#8217;ve made exactly this mistake in defining <code>cat1</code> above.
Consequently, each new phase will begin by responding to all of the old input and then carry on.
This meaning is both unintended and is very expensive (the dreaded &#8220;space-time&#8221; leak).</p>

<p>This difficulty is not unique to FRP.
In functional programming, we have to be careful how we hold onto our inputs, so that they can get accessed and freed incrementally.
I don&#8217;t think the difficulty arises much in imperative programming, because input (like output) is destructively altered, and programs have access only to the current state.</p>

<p>I&#8217;ve done it wrong above, in defining <code>cat</code>.
How can I do it right?
The solution/hack I came up for Fran was to add a function that trims (&#8220;ages&#8221;) dynamic input while waiting for event occurrences.</p>

<p><div>
<pre class="haskell">trim :: B b -&gt; E a -&gt; E <span style="color: green;">&#40;</span>a, B b<span style="color: green;">&#41;</span></pre>
</div></p>

<p><code>trim b e</code> follows <code>b</code> and <code>e</code> in parallel.
At each occurrence of <code>e</code>, the remainder of <code>b</code> is paired up with the event data from <code>e</code>.</p>

<p>Now I can define the interactive, multi-phase behavior I intend:</p>

<p><div>
<pre class="haskell">cat2 :: B World -&gt; B Cat
cat2 world = sleep world `switcher`
               <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:uncurry"><span style="font-weight: bold;">uncurry</span></a> prowl &lt;$&gt; trim world <span style="color: green;">&#40;</span>wake   world<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>`
                <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:uncurry"><span style="font-weight: bold;">uncurry</span></a> eat   &lt;$&gt; trim world <span style="color: green;">&#40;</span>hunger world<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre>
</div></p>

<p>The event <code>trim world (wake world)</code> occurs whenever <code>wake world</code> does, and has as event data the cat&#8217;s friskiness on waking, plus the remainder of the cat&#8217;s world at the occurrence time.
The &#8220;<code>uncurry prowl &lt;$&gt;</code>&#8221; applies <code>prowl</code> to each friskiness and remainder world on waking.
Similarly for the other phase.</p>

<p>I think this version defines the behavior I want and that it can run efficiently, assuming that <code>trim e b</code> traverses <code>e</code> and <code>b</code> in parallel (so that laziness doesn&#8217;t cause a space-time leak).
However, this definition is much trickier than what I&#8217;m looking for.</p>

<p>One small improvement is to abstract a trimming pattern:</p>

<p><div>
<pre class="haskell">trimf :: <span style="color: green;">&#40;</span>B i -&gt; E o<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>B i -&gt; E <span style="color: green;">&#40;</span>o, B i<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
trimf ef i = trim i <span style="color: green;">&#40;</span>ef i<span style="color: green;">&#41;</span>
&nbsp;
cat3 :: B World -&gt; B Cat
cat3 world = sleep world `switcher`
               <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:uncurry"><span style="font-weight: bold;">uncurry</span></a> prowl &lt;$&gt; trimf wake   world<span style="color: green;">&#41;</span> `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>`
                <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:uncurry"><span style="font-weight: bold;">uncurry</span></a> eat   &lt;$&gt; trimf hunger world<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre>
</div></p>

<h3>A comonad comes out of hiding</h3>

<p>The <code>trim</code> functions above look a lot like snapshotting of behaviors:</p>

<p><div>
<pre class="haskell">snapshot  :: B b -&gt; E a -&gt; E <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span>
&nbsp;
snapshot_ :: B b -&gt; E a -&gt; E b</pre>
</div></p>

<p>Indeed, the meanings of trimming and snapshotting are very alike.
They both involving following an event and a behavior in parallel.
At each event occurrence, <code>snapshot</code> takes the <em>value</em> of the behavior at the occurrence time, while <code>trim</code> takes the entire remainder from that time on.</p>

<p>Given this similarlity, can one be defined in terms of the other?
If we had a function to &#8220;extract&#8221; the first defined value of a behavior, we could define<code>snapshot</code> via <code>trim</code>.</p>

<p><div>
<pre class="haskell">b `snapshot` e = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Arrow.html#v:second"><span style="font-weight: bold;">second</span></a> extract<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>b `trim` e<span style="color: green;">&#41;</span>
&nbsp;
extract :: B a -&gt; a</pre>
</div></p>

<p>We can also define <code>trim</code> via <code>snapshot</code>, if we have a way to get all trimmed versions of a behavior &#8212; to &#8220;duplicate&#8221; a one-level behavior into a two-level behavior:</p>

<p><div>
<pre class="haskell">b `trim` e = duplicate b `snapshot` e
&nbsp;
duplicate :: B a -&gt; B <span style="color: green;">&#40;</span>B a<span style="color: green;">&#41;</span></pre>
</div></p>

<p>If you&#8217;ve run into comonads, you may recognize <code>extract</code> and <code>duplicate</code> as the operations of <code>Comonad</code>, dual to <code>Monad</code>&#8217;s <code>return</code> and <code>join</code>.
It was this definition of <code>trim</code> that got me interested in comonads recently.</p>

<p>In the style of <em><a href="http://conal.net/blog/posts/semantic-editor-combinators/" title="blog post">Semantic editor combinators</a></em>,</p>

<p><div>
<pre class="haskell">snapshot = <span style="color: green;">&#40;</span>result.result.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a>.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Arrow.html#v:second"><span style="font-weight: bold;">second</span></a><span style="color: green;">&#41;</span> extract trim</pre>
</div></p>

<p>or</p>

<p><div>
<pre class="haskell">trim = argument remainders R.snapshot</pre>
</div></p>

<p>The <code>extract</code> function is problematic for classic FRP, which uses absolute (global) time.
We don&#8217;t know with which time to sample the behavior.
With <em>relative-time FRP</em>, we&#8217;ll only ever sample at (local) time 0.</p>

<h3>Relative time</h3>

<p>So far, the necessary trimming has strong operational significance: it prevents obsolete reactions and the consequent space-time leaks.</p>

<p>If we switch from absolute time to relative time, then trimming becomes something with familiar semantics, namely <code>drop</code>, as generalized and used in two of my previous posts, <em><a href="http://conal.net/blog/posts/sequences-functions-and-segments/" title="blog post">Sequences, streams, and segments</a></em> and <em><a href="http://conal.net/blog/posts/sequences-segments-and-signals/" title="blog post">Sequences, segments, and signals</a></em>.</p>

<p>The semantic difference: trimming (absolute time) erases early content in an input; while dropping (relative time) shifts input backward in time, losing the early content in the same way as <code>drop</code> on sequences.</p>

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

<p>While input trimming can be managed systematically, doing so explicitly is tedious and error prone.
A follow-up post will automatically apply the techniques from this post.
Hiding and automating the mechanics of trimming allows interactive behavior to be expressed correctly and without distraction.</p>

<p>Another post will relate input trimming to the time transformation of interactive behaviors, as discussed in 
<em><a href="http://conal.net/blog/posts/why-classic-FRP-does-not-fit-interactive-behavior/" title="blog post">Why classic FRP does not fit interactive behavior</a></em>.</p>
]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/trimming-inputs-in-functional-reactive-programming/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Why classic FRP does not fit interactive behavior</title>
		<link>http://conal.net/blog/posts/why-classic-frp-does-not-fit-interactive-behavior/</link>
		<comments>http://conal.net/blog/posts/why-classic-frp-does-not-fit-interactive-behavior/#comments</comments>
		<pubDate>Wed, 10 Dec 2008 06:45:48 +0000</pubDate>
		<dc:creator>conal</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[FRP]]></category>
		<category><![CDATA[functional reactive programming]]></category>
		<category><![CDATA[interaction]]></category>
		<category><![CDATA[perspective]]></category>

		<guid isPermaLink="false">http://conal.net/blog/?p=69</guid>
		<description><![CDATA[]]></description>
			<content:encoded><![CDATA[<!-- 

Title: Why classic FRP does not fit interactive behavior

Tags: FRP, functional reactive programming, interaction, perspective

URL: http://conal.net/blog/posts/why-classic-FRP-does-not-fit-interactive-behavior/

-->

<!-- references -->

<!-- teaser -->

<p>In functional reactive programming (FRP), the type we call &#8220;behaviors&#8221; model <em>non-interactive</em> behavior.
To see why, just look at the semantic model: <code>t -&gt; a</code>, for some notion <code>t</code> of time.</p>

<p>One can argue as follows that this model applies to interactive behavior as well.
Behaviors interacting with inputs are functions of time and of inputs.
Those inputs are also functions of time, so behaviors are just functions of time.
I held this perspective at first, but came to see a lack of composability.</p>

<p>My original FRP formulations (<a href="http://conal.net/Fran" title="Functional reactive animation">Fran</a> and its predecessors <a href="http://conal.net/tbag/" title="Project web page">TBAG</a> and <a href="http://conal.net/papers/ActiveVRML/" title="Tech report: &quot;A Brief Introduction to ActiveVRML&quot;">ActiveVRML</a>), as well as the much more recent library <a href="http://haskell.org/haskellwiki/Reactive" title="Wiki page">Reactive</a>, can be and are used to describe interactive behavior.
For simple sorts of things, this use works out okay.
When applications get a bit richer, the interface and semantics strain.
If you&#8217;ve delved a bit, you&#8217;ll have run into the signs of strain, with coping mechanisms like <em>start times</em>, <em>user arguments</em> and <em>explicit aging</em> of inputs, as you avoid the dreaded <em>space-time leaks</em>.</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-69"></span></p>

<h3>Behaviors</h3>

<p>Suppose I define an object that pays attention to an input that&#8217;s interesting near a certain time.
For instance, a cat chasing a bird in the back yard one morning last week.
Now shift the behavior a week forward to this morning.
The result is just a week-delayed form of the earlier behavior, displaying reactions to week-old input.
The original interactive behavior (the cat) was fed input (bird and yard) from a week ago, the result was recorded, and that recording is replayed a week later.</p>

<p>Written functionally,</p>

<p><div>
<pre class="haskell">laterObserveCat :: Behavior World -&gt; Behavior Cat
laterObserveCat = later week . cat</pre>
</div></p>

<p>where</p>

<p><div>
<pre class="haskell">world :: Behavior World
cat   :: Behavior World -&gt; Behavior Cat
&nbsp;
later :: Duration -&gt; Behavior a -&gt; Behavior a</pre>
</div></p>

<p>We can also sit in the living room, five meters north of the back yard, and watch the cat via a camera.</p>

<p><div>
<pre class="haskell">livingRoomObserveCat :: Behavior World -&gt; Behavior Cat
livingRoomObserveCat = north <span style="color: green;">&#40;</span><span style="color: red;">5</span> * meter<span style="color: green;">&#41;</span> . cat</pre>
</div></p>

<p>Typically recordings are moved <em>both</em> in space and in time.
For example, record the cat in the back yard one week and watch the recording in the living room a week later:</p>

<p><div>
<pre class="haskell">replayLRL :: Behavior World -&gt; Behavior Cat
replayLRL = later week . north <span style="color: green;">&#40;</span><span style="color: red;">5</span> * meter<span style="color: green;">&#41;</span> . cat</pre>
</div></p>

<h3>Interactive behavior</h3>

<p>I&#8217;ve just described transforming a <em>non-interactive</em> behavior (recording) in time and space.
That non-interactive behavior resulted applying an interactive behavior (the cat) to some input (bird and yard).
An <em>interactive</em> behavior is simply a function from non-interactive behavior (time-varying input) to non-interactive behavior (time-varying output).</p>

<p>Consider what it means to transform an <em>interactive</em> behavior in space.
I pick up the cat and carry her five meters north, into the living room.
The cat has a different perspective, which is that her environment moves five meters south.
For instance, the mouse that was one meter south of her is now six meters sounth.</p>

<p>If I lift the cat four feet above the ground, she sees the ground now four <em>below</em> her.
If I spin her clockwise, her environment spins counter-clockwise.
If I point my shrinking ray at her, she sees her world as growing larger, and she flees from the giant mice.</p>

<p>We can play the perspective game in time as well as space.
I point my speed-up ray at the cat, and she perceives her environment slow down.</p>

<p>When I say I move the cat north and she see her environment move south, I am not suggesting that there are two alternative perspectives and we might take either one.
Rather, a complete picture combines both movements.
The behavior my cat exhibits when I pick her up is composed of three transformations:</p>

<ul>
<li>The world moves south;</li>
<li>The cat perceives this more southerly world and responds to it; and</li>
<li>The resulting cat behavior is moved north.</li>
</ul>

<p>Written functionally,</p>

<p><div>
<pre class="haskell">livingRoomCat :: Behavior World -&gt; Behavior Cat
livingRoomCat = north <span style="color: green;">&#40;</span><span style="color: red;">5</span> * meter<span style="color: green;">&#41;</span> . cat . south <span style="color: green;">&#40;</span><span style="color: red;">5</span> * meter<span style="color: green;">&#41;</span></pre>
</div></p>

<p>Similarly with other spatial transformation, each with paired inverse transformations.
And similarly in time, e.g.,</p>

<p><div>
<pre class="haskell">laterCat :: Behavior World -&gt; Behavior Cat
laterCat = later week . cat . earlier week</pre>
</div></p>

<p>So there&#8217;s a semantically consistent model of transforming interactive behaviors in time or space, and this model explains the difference between transformation of non-interactive behavior and of interactive behavior.</p>

<h3>Aside</h3>

<p>Comparing these two definitions with the previous two suggests an alternative implementation.
Refactoring,</p>

<p><div>
<pre class="haskell">laterCat :: Behavior World -&gt; Behavior Cat
laterCat = laterObserveCat . earlier week</pre>
</div></p>

<p>Instead of carrying the interactive cat a week ahead in time, this definition suggests that we move the world (other than the cat) <em>back</em> one week, record the cat interacting with it, and hold onto that recording to watch a week later.
My back-of-the-envelope calculations suggest that this second implementation is less resource-efficient than the first one, so I&#8217;ll not consider it further in this post.</p>

<h3>Arrow FRP</h3>

<p>When we use for an interactive setting the tools suited to non-interactive behaviors, we&#8217;re begging for space leaks (filling up recording media) and time leaks (fast-forwarding through old recorded matter to catch up with what we want to see).
These problems are what people experience when programming explicitly with  might call &#8220;classic FRP&#8221;, i.e., programming explicitly with (non-interactive) behaviors.
Out of this experience was born &#8220;Arrow FRP&#8221;, as in <a href="http://conal.net/papers/genuinely-functional-guis.pdf" title="Paper: &quot;Genuinely Functional User Interfaces&quot;">Fruit</a> and <a href="http://haskell.org/haskellwiki/Yampa" title="Wiki page">Yampa</a>.
The idea of Arrow FRP was to program with a type of &#8220;signal functions&#8221;, which can be thought of as mappings between behaviors:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">type</span> SF a b = Behavior a -&gt; Behavior b</pre>
</div></p>

<p>(Behaviors were also renamed to &#8220;signals&#8221;, but I&#8217;ll stick with &#8220;behaviors&#8221; for now.)
We can just look at semantic model for signal transformers and see that they&#8217;re about <em>interactive</em> behavior.</p>

<p>A lot of work was done with this new model, mostly growing out of Paul Hudak&#8217;s group at Yale.
It addressed the inherent awkwardness of the explicit-behavior style.</p>

<p>Despite this fundamental advantage of signal transformers, why am I still fooling around with the &#8220;classic&#8221; (pre-arrow) style?</p>

<ul>
<li>The <code>Arrow</code> style required multiple behaviors to be bunched up into one.  That combination appears to thwart efficient, change-driven evaluation, which was the problem I tackled in <em><a href="http://conal.net/blog/posts/simply-efficient-functional-reactivity/" title="Blog post">Simply efficient functional reactivity</a></em>.</li>
<li>There was no room for the distinction between behaviors and events.  I&#8217;d love to see how to combine them without losing expressiveness or semantic accuracy, and I haven&#8217;t yet.</li>
<li>Arrow programming is very awkward without the special arrow notation and has more of a sequential style than I like with the arrow notation.  I missed the functional feel of classic FRP.</li>
</ul>

<h3>Coming up</h3>

<p>Given the fundamental semantic fit between signal transformers for the problem domain of interactive behavior, I&#8217;d like to come up wh convenient and efficient packaging.
The next posts will describe the packaging I&#8217;m trying out now.</p>
]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/why-classic-frp-does-not-fit-interactive-behavior/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Sequences, segments, and signals</title>
		<link>http://conal.net/blog/posts/sequences-segments-and-signals/</link>
		<comments>http://conal.net/blog/posts/sequences-segments-and-signals/#comments</comments>
		<pubDate>Fri, 05 Dec 2008 08:14:33 +0000</pubDate>
		<dc:creator>conal</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[applicative functor]]></category>
		<category><![CDATA[comonad]]></category>
		<category><![CDATA[FRP]]></category>
		<category><![CDATA[function]]></category>
		<category><![CDATA[functional reactive programming]]></category>
		<category><![CDATA[functor]]></category>
		<category><![CDATA[monoid]]></category>
		<category><![CDATA[segment]]></category>
		<category><![CDATA[sequence]]></category>
		<category><![CDATA[type class morphism]]></category>

		<guid isPermaLink="false">http://conal.net/blog/?p=67</guid>
		<description><![CDATA[]]></description>
			<content:encoded><![CDATA[<!-- 

Title: Sequences, segments, and signals

Tags: function, sequence, monoid, functor, applicative functor, comonad, FRP, functional reactive programming, segment, type class morphism

URL: http://conal.net/blog/posts/sequences-segments-and-signals/

-->

<!-- references -->

<!-- teaser -->

<p>The post <em><a href="http://conal.net/blog/posts/sequences-streams-and-segments/" title="blog post">Sequences, streams, and segments</a></em> offered an answer to the the question of what&#8217;s missing in the following box:</p>

<div align=center style="margin-bottom:10px">
  <table border="2">
    <tr><td></td><td style="text-align:center;padding:5px"><strong>infinite</strong><td style="text-align:center;padding:5px"><strong>finite</strong></third></tr>
    <tr><td style="text-align:center;padding:5px"><strong>discrete</strong><td style="text-align:center;padding:7px">Stream</td> <td style="text-align:center;padding:7px">Sequence</td></tr>
    <tr><td style="text-align:center;padding:5px"><strong>continuous</strong><td style="text-align:center;padding:7px">Function</td> <td style="text-align:center;padding:7px"><em>???</em></td></tr>
  </table>
</div>

<p>I presented a simple type of <em>function segments</em>, whose representation contains a length (duration) and a function.
This type implements most of the usual classes: <code>Monoid</code>, <code>Functor</code>, <code>Zip</code>, and <code>Applicative</code>, as well <code>Comonad</code>, but not <code>Monad</code>.
It also implements a new type class, <code>Segment</code>, which generalizes the list functions <code>length</code>, <code>take</code>, and <code>drop</code>.</p>

<p>The function type is simple and useful in itself.
I believe it can also serve as a semantic foundation for functional reactive programming (FRP), as I&#8217;ll explain in another post.
However, the type has a serious performance problem that makes it impractical for some purposes, including as implementation of FRP.</p>

<p>Fortunately, we can solve the performance problem by adding a simple layer on top of function segments, to get what I&#8217;ll call &#8220;signals&#8221;.
With this new layer, we have an efficient replacement for function segments that implements exactly the same interface with exactly the same semantics.
Pleasantly, the class instances are defined fairly simply in terms of the corresponding instances on function segments.</p>

<p>You can download the <a href="http://conal.net/blog/code/Signal.hs">code for this post</a>.</p>

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

<ul>
<li>2008-12-06: <code>dup [] = []</code> near the end (was <code>[mempty]</code>).</li>
<li>2008-12-09: Fixed <code>take</code> and <code>drop</code> default definitions (thanks to sclv) and added point-free variant.</li>
<li>2008-12-18: Fixed <code>appl</code>, thanks to sclv.</li>
</ul>

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

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

<h3>The problem with function segments</h3>

<p>The type of function segments is defined as follows:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">data</span> t :-&gt;# a = FS t <span style="color: green;">&#40;</span>t -&gt; a<span style="color: green;">&#41;</span></pre>
</div></p>

<p>The domain of the function segment is from zero up to but not including the given length.</p>

<p>An efficiency problem becomes apparent when we look at the <code>Monoid</code> instance:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> t, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="color: #833; font-weight: bold;">Num</span></a> t<span style="color: green;">&#41;</span> =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> <span style="color: green;">&#40;</span>t :-&gt;# a<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a> = FS <span style="color: red;">0</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:error"><span style="font-weight: bold;">error</span></a> <span style="color: green;">&quot;sampling empty 't :-&gt;# a'&quot;</span><span style="color: green;">&#41;</span>
    FS c f `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` FS d g =
      FS <span style="color: green;">&#40;</span>c + d<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>\ t -&gt; <span style="color: #050; font-weight: bold;">if</span> t &lt;= c <span style="color: #050; font-weight: bold;">then</span> f t <span style="color: #050; font-weight: bold;">else</span> g <span style="color: green;">&#40;</span>t - c<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre>
</div></p>

<p>Concatenation (<code>mappend</code>) creates a new segment that chooses, for every domain value <code>t</code>, whether to use one function or another.
If the second, then <code>t</code> must be shifted backward, since the function is being shifted forward.</p>

<p>This implementation would be fine if we use <code>mappend</code> just on simple segments.
Once we get started, however, we&#8217;ll want to concatenate lots &amp; lots of segments.
In FRP, time-varying values go through many phases (segments) as time progresses.
Each quantity is described by a single &#8220;behavior&#8221; (sometimes called a &#8220;signal&#8221;) with many, and often infinitely many, phases.
Imagine an infinite tree of concatenations, which is typical for FRP behaviors.
At every moment, one phase is active.
Every sampling must recursively discover the active phase and the accumulated domain translation (from successive subtractions) to apply when sampling that phase.
Quite commonly, concatenation trees get progressively deeper on the right (larger <code>t</code> values).
In that case, sampling will get slower and slower with time.</p>

<p>I like to refer to these progressive slow-downs as &#8220;time leaks&#8221;.
There is also a serious space leak, since all of the durations and functions that go into a composed segment will be retained.</p>

<h3>Sequences of segments</h3>

<p>The problem above can be solved with a simple representation change.
Instead of combining functions into functions, just keep a list of simple function segments.</p>

<p><div>
<pre class="haskell"><span style="color: #5d478b; font-style: italic;">-- | Signal indexed by t with values of type a.</span>
<span style="color: #050; font-weight: bold;">newtype</span> t :-&gt; a = S <span style="color: green;">&#123;</span> unS :: <span style="color: green;">&#91;</span>t :-&gt;# a<span style="color: green;">&#93;</span> <span style="color: green;">&#125;</span></pre>
</div></p>

<p>I&#8217;ll restrict in function segments to be <em>non-empty</em>, to keep the rest of the implementation simple and efficient.</p>

<p>This new representation allows for efficient <em>monotonic</em> sampling of signals.
As old segments are passed up, they can be dropped.</p>

<h4>What does it mean?</h4>

<p>There&#8217;s one central question for me in defining any data type: <em>What does it mean?</em></p>

<p>The meaning I&#8217;ll take for signals is function segments.
This interpretation is made precise in a function that maps from the type to the model (meaning).
In this case, simply concatenate all of the function segments:</p>

<p><div>
<pre class="haskell">meaning :: <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> t, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="color: #833; font-weight: bold;">Num</span></a> t<span style="color: green;">&#41;</span> =&gt; <span style="color: green;">&#40;</span>t :-&gt; a<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>t :-&gt;# a<span style="color: green;">&#41;</span>
meaning = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mconcat"><span style="font-weight: bold;">mconcat</span></a> . unS</pre>
</div></p>

<p>Specifying the meaning of a type gives users a working model, and it defines correctness of implementation.
It also tells me what class instances to implement and tells users what instances to expect.
If a type&#8217;s meaning implements a class then I want the type to as well.
Moreover, the type&#8217;s intances have to agree with the model&#8217;s instances.
I&#8217;ve described this latter principle in <em><a href="http://conal.net/blog/posts/simplifying-semantics-with-type-class-morphisms" title="blog post">Simplifying semantics with type class morphisms</a></em> and <a href="http://conal.net/blog/tag/type-class-morphism/" title="Posts on type class morphisms">some other posts</a>.</p>

<h4>Higher-order wrappers</h4>

<p>To keep the code below short and clear, I&#8217;ll use some functions for adding and removing the newtype wrappers.
These higher-order function apply functions inside of <code>(:-&gt;)</code> representations:</p>

<p><div>
<pre class="haskell">inS  :: <span style="color: green;">&#40;</span><span style="color: green;">&#91;</span>s :-&gt;# a<span style="color: green;">&#93;</span> -&gt; <span style="color: green;">&#91;</span>t :-&gt;# b<span style="color: green;">&#93;</span><span style="color: green;">&#41;</span>
     -&gt; <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>s :-&gt;  a<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>t :-&gt;  b<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
inS2 :: <span style="color: green;">&#40;</span><span style="color: green;">&#91;</span>s :-&gt;# a<span style="color: green;">&#93;</span> -&gt; <span style="color: green;">&#91;</span>t :-&gt;# b<span style="color: green;">&#93;</span> -&gt; <span style="color: green;">&#91;</span>u :-&gt;# c<span style="color: green;">&#93;</span><span style="color: green;">&#41;</span>
     -&gt; <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>s :-&gt;  a<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>t :-&gt;  b<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>u :-&gt;  c<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre>
</div></p>

<p>Using the trick described in <em><a href="http://conal.net/blog/posts/prettier-functions-for-wrapping-and-wrapping/" title="blog post">Prettier functions for wrapping and wrapping</a></em>, the definitions are simpler than the types:</p>

<p><div>
<pre class="haskell">inS  = result   S . argument unS
inS2 = result inS . argument unS</pre>
</div></p>

<h4><code>Functor</code></h4>

<p>The <code>Functor</code> instance applies a given function inside the function segments inside the lists:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="color: #833; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>:-&gt;<span style="color: green;">&#41;</span> t<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> h <span style="color: green;">&#40;</span>S ss<span style="color: green;">&#41;</span> = S <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> h<span style="color: green;">&#41;</span> ss<span style="color: green;">&#41;</span></pre>
</div></p>

<p>Or, in the style of <em><a href="http://conal.net/blog/posts/semantic-editor-combinators/" title="blog post">Semantic editor combinators</a></em>,</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="color: #833; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>:-&gt;<span style="color: green;">&#41;</span> t<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> = inS . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a></pre>
</div></p>

<p>Why this definition?
Because it is correct with respect to the semantic model, i.e., the meaning of <code>fmap</code> is <code>fmap</code> of the meaning, i.e.,</p>

<p><div>
<pre class="haskell"> meaning . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> h == <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> h . meaning</pre>
</div></p>

<p>which is to say that the following diagram commutes:</p>

<div align=center><img src="http://conal.net/blog/pictures/signal-meaning-fmap-morphism.png"/></div>

<p>Proof:</p>

<p><div>
<pre class="haskell">meaning . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> h 
&nbsp;
  == <span style="color: #5d478b; font-style: italic;">{- fmap definition -}</span>
&nbsp;
meaning . S . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> h<span style="color: green;">&#41;</span> . unS
&nbsp;
  == <span style="color: #5d478b; font-style: italic;">{- meaning definition -}</span>
&nbsp;
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mconcat"><span style="font-weight: bold;">mconcat</span></a> . unS . S . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> h<span style="color: green;">&#41;</span> . unS
&nbsp;
  == <span style="color: #5d478b; font-style: italic;">{- unS and S are inverses  -}</span>
&nbsp;
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mconcat"><span style="font-weight: bold;">mconcat</span></a> . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> h<span style="color: green;">&#41;</span> . unS
&nbsp;
  == <span style="color: #5d478b; font-style: italic;">{- fmap h distributes over mappend -}</span>
&nbsp;
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> h . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mconcat"><span style="font-weight: bold;">mconcat</span></a> . unS
&nbsp;
  == <span style="color: #5d478b; font-style: italic;">{- meaning definition -}</span>
&nbsp;
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> . meaning</pre>
</div></p>

<h4><code>Applicative</code> and <code>Zip</code></h4>

<p>Again, the <code>meaning</code> functions tells us what the <code>Applicative</code> instance has to mean.
We only get to choose how to implement that meaning correctly.
The <code>Applicative</code> <a href="http://conal.net/blog/tag/type-class-morphism/" title="Posts on type class morphisms">morphism properties</a>:</p>

<p><div>
<pre class="haskell">meaning <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a> a<span style="color: green;">&#41;</span>    == <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a> a
meaning <span style="color: green;">&#40;</span>bf &lt;*&gt; bx<span style="color: green;">&#41;</span> == meaning bf &lt;*&gt; meaning bx</pre>
</div></p>

<p>Our <code>Applicative</code> instance has a definition similar in simplicity and style to the <code>Functor</code> instance, assuming a worker function <code>appl</code> for <code>(&lt;*&gt;)</code>:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> t, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="color: #833; font-weight: bold;">Num</span></a> t, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bounded"><span style="color: #833; font-weight: bold;">Bounded</span></a> t<span style="color: green;">&#41;</span> =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#t:Applicative"><span style="color: #833; font-weight: bold;">Applicative</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>:-&gt;<span style="color: green;">&#41;</span> t<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a>  = S . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a> . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a>
    <span style="color: green;">&#40;</span>&lt;*&gt;<span style="color: green;">&#41;</span> = inS2 appl
&nbsp;
appl :: <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> t, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="color: #833; font-weight: bold;">Num</span></a> t, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bounded"><span style="color: #833; font-weight: bold;">Bounded</span></a> t<span style="color: green;">&#41;</span> =&gt;
        <span style="color: green;">&#91;</span>t :-&gt;# <span style="color: green;">&#40;</span>a -&gt; b<span style="color: green;">&#41;</span><span style="color: green;">&#93;</span> -&gt; <span style="color: green;">&#91;</span>t :-&gt;# a<span style="color: green;">&#93;</span> -&gt; <span style="color: green;">&#91;</span>t :-&gt;# b<span style="color: green;">&#93;</span></pre>
</div></p>

<p>This worker function is somewhat intricate.
At least my implementation of it is, and perhaps there&#8217;s a simpler one.</p>

<p>Again, the <code>meaning</code> functions tells us what the <code>Applicative</code> instance has to mean.
We only get to choose how to implement that meaning correctly.</p>

<p>First, if either segment list runs out, the combination runs out (because the same is true for the <em>meaning</em> of signals).</p>

<p><div>
<pre class="haskell"><span style="color: green;">&#91;</span><span style="color: green;">&#93;</span> `appl` _  = <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span>
&nbsp;
_  `appl` <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span> = <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span></pre>
</div></p>

<p>If neither segment list is empty, open up the first segment.
Split the longer segment into a prefix that matches the shorter segment, and combine the two segments with <code>(&lt;*&gt;)</code> (on function segments).
Toss the left-over piece back in its list, and continue.</p>

<p><div>
<pre class="haskell"><span style="color: green;">&#40;</span>fs:fss'<span style="color: green;">&#41;</span> `appl` <span style="color: green;">&#40;</span>xs:xss'<span style="color: green;">&#41;</span>
   | fd == xd  = <span style="color: green;">&#40;</span>fs  &lt;*&gt; xs <span style="color: green;">&#41;</span> : <span style="color: green;">&#40;</span>fss' `appl`       xss' <span style="color: green;">&#41;</span>
   | fd &lt;  xd  = <span style="color: green;">&#40;</span>fs  &lt;*&gt; xs'<span style="color: green;">&#41;</span> : <span style="color: green;">&#40;</span>fss' `appl` <span style="color: green;">&#40;</span>xs'':xss'<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
   | <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:otherwise"><span style="font-weight: bold;">otherwise</span></a> = <span style="color: green;">&#40;</span>fs' &lt;*&gt; xs <span style="color: green;">&#41;</span> : <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>fs'':fss'<span style="color: green;">&#41;</span> `appl` xss'<span style="color: green;">&#41;</span>
 <span style="color: #050; font-weight: bold;">where</span>
   fd         = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:length"><span style="font-weight: bold;">length</span></a> fs
   xd         = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:length"><span style="font-weight: bold;">length</span></a> xs
   <span style="color: green;">&#40;</span>fs',fs''<span style="color: green;">&#41;</span> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:splitAt"><span style="font-weight: bold;">splitAt</span></a> xd fs
   <span style="color: green;">&#40;</span>xs',xs''<span style="color: green;">&#41;</span> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:splitAt"><span style="font-weight: bold;">splitAt</span></a> fd xs</pre>
</div></p>

<p>A <code>Zip</code> instance is easy as always with applicative functors:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> t, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="color: #833; font-weight: bold;">Num</span></a> t, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bounded"><span style="color: #833; font-weight: bold;">Bounded</span></a> t<span style="color: green;">&#41;</span> =&gt; Zip <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>:-&gt;<span style="color: green;">&#41;</span> t<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:zip"><span style="font-weight: bold;">zip</span></a> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:liftA2"><span style="font-weight: bold;">liftA2</span></a> <span style="color: green;">&#40;</span>,<span style="color: green;">&#41;</span></pre>
</div></p>

<h4><code>Monoid</code></h4>

<p>The <code>Monoid</code> instance:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> <span style="color: green;">&#40;</span>t :-&gt; a<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a> = S <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span>
  S xss `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` S yss = S <span style="color: green;">&#40;</span>xss ++ yss<span style="color: green;">&#41;</span></pre>
</div></p>

<p>Correctness follows from properties of <code>mconcat</code> (as used in the <code>meaning</code> function).</p>

<p>We&#8217;re really just using the <code>Monoid</code> instance for the underlying representation, i.e.,</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> <span style="color: green;">&#40;</span>t :-&gt; a<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>  = S <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a> = inS2 <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a></pre>
</div></p>

<h4><code>Segment</code></h4>

<p>The <code>Segment</code> class has <code>length</code>, <code>take</code> and <code>drop</code>.
It&#8217;s handy to include also <code>null</code> and <code>splitAt</code>, both modeled after their counterparts on lists.</p>

<p>The new &amp; improved <code>Segment</code> class:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">class</span> Segment seg dur | seg -&gt; dur <span style="color: #050; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:null"><span style="font-weight: bold;">null</span></a>    :: seg -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="color: #833; font-weight: bold;">Bool</span></a>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:length"><span style="font-weight: bold;">length</span></a>  :: seg -&gt; dur
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:take"><span style="font-weight: bold;">take</span></a>    :: dur -&gt; seg -&gt; seg
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:drop"><span style="font-weight: bold;">drop</span></a>    :: dur -&gt; seg -&gt; seg
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:splitAt"><span style="font-weight: bold;">splitAt</span></a> :: dur -&gt; seg -&gt; <span style="color: green;">&#40;</span>seg,seg<span style="color: green;">&#41;</span>
    <span style="color: #5d478b; font-style: italic;">-- Defaults:</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:splitAt"><span style="font-weight: bold;">splitAt</span></a> d s = <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:take"><span style="font-weight: bold;">take</span></a> d s, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:drop"><span style="font-weight: bold;">drop</span></a> d s<span style="color: green;">&#41;</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:take"><span style="font-weight: bold;">take</span></a>    d s = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fst"><span style="font-weight: bold;">fst</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:splitAt"><span style="font-weight: bold;">splitAt</span></a> d s<span style="color: green;">&#41;</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:drop"><span style="font-weight: bold;">drop</span></a>    d s = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:snd"><span style="font-weight: bold;">snd</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:splitAt"><span style="font-weight: bold;">splitAt</span></a> d s<span style="color: green;">&#41;</span></pre>
</div></p>

<p>If we wanted to require <code>dur</code> to be numeric, we could add a default for <code>null</code> as well.
This default could be quite expensive in some cases.
(In the style of <em><a href="http://conal.net/blog/posts/semantic-editor-combinators/" title="blog post">Semantic editor combinators</a></em>, <code>take = (result.result) fst splitAt</code>, and similarly for <code>drop</code>.)</p>

<p>The <code>null</code> and <code>length</code> definitions are simple, following from to properties of <code>mconcat</code>.</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> t, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="color: #833; font-weight: bold;">Num</span></a> t<span style="color: green;">&#41;</span> =&gt; Segment <span style="color: green;">&#40;</span>t :-&gt; a<span style="color: green;">&#41;</span> t <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:null"><span style="font-weight: bold;">null</span></a>   <span style="color: green;">&#40;</span>S xss<span style="color: green;">&#41;</span> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:null"><span style="font-weight: bold;">null</span></a> xss
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:length"><span style="font-weight: bold;">length</span></a> <span style="color: green;">&#40;</span>S xss<span style="color: green;">&#41;</span> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:sum"><span style="font-weight: bold;">sum</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:length"><span style="font-weight: bold;">length</span></a> &lt;$&gt; xss<span style="color: green;">&#41;</span>
  ...</pre>
</div></p>

<p>The null case says that the signal is empty exactly when there are no function segments.
This simple definition relies on our restriction to non-empty function segments.
If we drop that restriction, we&#8217;d have to check that every segment is empty:</p>

<p><div>
<pre class="haskell">  <span style="color: #5d478b; font-style: italic;">-- Alternative definition</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:null"><span style="font-weight: bold;">null</span></a> <span style="color: green;">&#40;</span>S xss<span style="color: green;">&#41;</span> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:all"><span style="font-weight: bold;">all</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:null"><span style="font-weight: bold;">null</span></a> xss</pre>
</div></p>

<p>The <code>length</code> is just the sum of the lengths.</p>

<p>The tricky piece is <code>splitAt</code> (used to define both <code>take</code> and drop), which must assemble segments to satisfy the requested prefix length.
The last segment used might have to get split into two, with one part going into the prefix and one to the suffix.</p>

<p><div>
<pre class="haskell">  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:splitAt"><span style="font-weight: bold;">splitAt</span></a> _ <span style="color: green;">&#40;</span>S <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span><span style="color: green;">&#41;</span>  = <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>,<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a><span style="color: green;">&#41;</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:splitAt"><span style="font-weight: bold;">splitAt</span></a> d b | d &lt;= <span style="color: red;">0</span> = <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>, b<span style="color: green;">&#41;</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:splitAt"><span style="font-weight: bold;">splitAt</span></a> d <span style="color: green;">&#40;</span>S <span style="color: green;">&#40;</span>xs:xss'<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> =
    <span style="color: #050; font-weight: bold;">case</span> <span style="color: green;">&#40;</span>d `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:compare"><span style="font-weight: bold;">compare</span></a>` xd<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">of</span>
      EQ -&gt; <span style="color: green;">&#40;</span>S <span style="color: green;">&#91;</span>xs<span style="color: green;">&#93;</span>, S xss'<span style="color: green;">&#41;</span>
      LT -&gt; <span style="color: #050; font-weight: bold;">let</span> <span style="color: green;">&#40;</span>xs',xs''<span style="color: green;">&#41;</span> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:splitAt"><span style="font-weight: bold;">splitAt</span></a> d xs <span style="color: #050; font-weight: bold;">in</span>
              <span style="color: green;">&#40;</span>S <span style="color: green;">&#91;</span>xs'<span style="color: green;">&#93;</span>, S <span style="color: green;">&#40;</span>xs'':xss'<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
      GT -&gt; <span style="color: #050; font-weight: bold;">let</span> <span style="color: green;">&#40;</span>S uss, suffix<span style="color: green;">&#41;</span> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:splitAt"><span style="font-weight: bold;">splitAt</span></a> <span style="color: green;">&#40;</span>d-xd<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>S xss'<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">in</span>
              <span style="color: green;">&#40;</span>S <span style="color: green;">&#40;</span>xs:uss<span style="color: green;">&#41;</span>, suffix<span style="color: green;">&#41;</span>
   <span style="color: #050; font-weight: bold;">where</span>
     xd = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:length"><span style="font-weight: bold;">length</span></a> xs</pre>
</div></p>

<h4><code>Copointed</code> and <code>Comonad</code></h4>

<p>To extract an element from a signal, extract an element from its first function segment.
Awkwardly, extraction will fail (produce &perp;/error) when the signal is empty.</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="color: #833; font-weight: bold;">Num</span></a> t =&gt; Copointed <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>:-&gt;<span style="color: green;">&#41;</span> t<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
    extract <span style="color: green;">&#40;</span>S <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span><span style="color: green;">&#41;</span>     = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:error"><span style="font-weight: bold;">error</span></a> <span style="color: green;">&quot;extract: empty S&quot;</span>
    extract <span style="color: green;">&#40;</span>S <span style="color: green;">&#40;</span>xs:_<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> = extract xs</pre>
</div></p>

<p>I&#8217;ve exploited our restriction to non-empty function segments.
Otherwise, <code>extract</code> would have to skip past the empty ones:</p>

<p><div>
<pre class="haskell"><span style="color: #5d478b; font-style: italic;">-- Alternative definition</span>
<span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="color: #833; font-weight: bold;">Num</span></a> t =&gt; Copointed <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>:-&gt;<span style="color: green;">&#41;</span> t<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
    extract <span style="color: green;">&#40;</span>S <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span><span style="color: green;">&#41;</span> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:error"><span style="font-weight: bold;">error</span></a> <span style="color: green;">&quot;extract: empty S&quot;</span>
    extract <span style="color: green;">&#40;</span>S <span style="color: green;">&#40;</span>xs:xss'<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
      | <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:null"><span style="font-weight: bold;">null</span></a> xs     = extract <span style="color: green;">&#40;</span>S xss'<span style="color: green;">&#41;</span>
      | <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:otherwise"><span style="font-weight: bold;">otherwise</span></a>   = extract xs</pre>
</div></p>

<p>The error/&perp; in this definition is dicey, as is the one for function segments.
If we allow the same abuse in order to define a list <code>Copointed</code>, we can get an alternative to the first definition that is prettier but gives a less helpful error message:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="color: #833; font-weight: bold;">Num</span></a> t =&gt; Copointed <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>:-&gt;<span style="color: green;">&#41;</span> t<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
    extract = extract . extract . unS</pre>
</div></p>

<p>See the closing remarks for more about this diciness.</p>

<p>Finally, we have <code>Comonad</code>, with its <code>duplicate</code> method.</p>

<p><div>
<pre class="haskell">duplicate :: <span style="color: green;">&#40;</span>t :-&gt; a<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>t :-&gt; <span style="color: green;">&#40;</span>t :-&gt; a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre>
</div></p>

<p>I get confused with wrapping and unwrapping, so let&#8217;s separate the definition into a packaging part and a content part.</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> t, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="color: #833; font-weight: bold;">Num</span></a> t<span style="color: green;">&#41;</span> =&gt; Comonad <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>:-&gt;<span style="color: green;">&#41;</span> t<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
    duplicate = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> S . inS dup</pre>
</div></p>

<p>with content part:</p>

<p><div>
<pre class="haskell">dup :: <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> t, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="color: #833; font-weight: bold;">Num</span></a> t<span style="color: green;">&#41;</span> =&gt; <span style="color: green;">&#91;</span>t :-&gt;# a<span style="color: green;">&#93;</span> -&gt; <span style="color: green;">&#91;</span>t :-&gt;# <span style="color: green;">&#91;</span>t :-&gt;# a<span style="color: green;">&#93;</span><span style="color: green;">&#93;</span></pre>
</div></p>

<p><!-- 
I think of `duplicate` as forming all of the *tails* of a segment (as it does with lists via the standard `tails` function). 
-->
The helper function, <code>dup</code>, takes each function segment and prepends each of its tails onto the remaining list of segments.</p>

<p>If the segment list is empty, then it has only one tail, also empty.</p>

<p><div>
<pre class="haskell">dup <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span>        = <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span>
&nbsp;
dup <span style="color: green;">&#40;</span>xs:xss'<span style="color: green;">&#41;</span> = <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span> <img src='http://conal.net/blog/wp-includes/images/smilies/icon_mad.gif' alt=':x' class='wp-smiley' /> ss'<span style="color: green;">&#41;</span> &lt;$&gt; duplicate xs<span style="color: green;">&#41;</span> : dup xss'</pre>
</div></p>

<h3>Closing remarks</h3>

<ul>
<li><p>The definitions above use the function segment type only through its type class interfaces, and so can all of them can be generalized.
Several definitions rely on the <code>Segment</code> instance, but otherwise, each method for the composite type relies on the corresponding method for the underlying segment type.
(For instance, <code>fmap</code> uses <code>fmap</code>, <code>(&lt;*&gt;)</code> uses <code>(&lt;*&gt;)</code>, <code>Segment</code> uses <code>Segment</code>, etc.)
This generality lets us replace function segments with more efficient representations, e.g., doing constant propagation, as in <a href="http://haskell.org/haskellwiki/Reactive" title="Wiki page for the Reactive library">Reactive</a>.
We can also generalize from lists in the definitions above.</p></li>
<li><p>Even without concatenation, function segments can become expensive when <code>drop</code> is repeatedly applied, because function shifts accumulate (e.g., <code>f . (+ 0.01) . (+ 0.01) ....</code>).
A more <code>drop</code>-friendly representation for function segments would be a function and an offset.
Successive drops would add offsets, and <code>extract</code> would always apply the function to its offset.
This representation is similar to the <code>FunArg</code> comonad, mentioned in <a href="http://cs.ioc.ee/~tarmo/papers/essence.pdf" title="Paper by Tarmo Uustalu and Varmo Vene">The Essence of Dataflow Programming</a> (Section 5.2).</p></li>
<li><p>The list-of-segments representation enables efficient monotonic sampling, simply by dropping after each sample.
A variation is to use a list zipper instead of a list.
Then one can non-monotonically, and sampling will be efficient as long as successive samplings are for nearby domain values.
Switching to multi-directional representation would lose the space efficiency of unidirectional representations.
The latter work well with lazy evaluation, often running in constant space, because old values are recycled while new values are getting evaluated.</p></li>
<li><p>Still another variation is to use a binary tree instead of a list, to avoid the list append in the <code>Monoid</code> instance for <code>(t :-&gt; a)</code>.
A tree zipper would allow non-monotonic sampling.
Sufficient care in data structure design could perhaps yield efficient random access.</p></li>
<li><p>There&#8217;s a tension between the <code>Copointed</code> and <code>Monoid</code> interfaces.
<code>Copointed</code> has <code>extract</code>, and <code>Monoid</code> has <code>mempty</code>, so what is the value of <code>extract mempty</code>?
Given that <code>Copointed</code> is parameterized over <em>arbitrary</em> types, the only possible answer seems to be &perp; (as in the use of <code>error</code> above).
I don&#8217;t know if the comonad laws can all hold for possibly-empty function segments or for possibly-empty signals.
I&#8217;m grateful to <a href="http://comonad.com/reader/">Edward Kmett</a> for helping me understand this conflict.
He suggested using two coordinated types, one possibly-empty (a monoid) and the other non-empty (a comonad).
I&#8217;m curious to see whether that idea works out.</p></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/sequences-segments-and-signals/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Sequences, streams, and segments</title>
		<link>http://conal.net/blog/posts/sequences-streams-and-segments/</link>
		<comments>http://conal.net/blog/posts/sequences-streams-and-segments/#comments</comments>
		<pubDate>Mon, 01 Dec 2008 07:29:27 +0000</pubDate>
		<dc:creator>conal</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[applicative functor]]></category>
		<category><![CDATA[comonad]]></category>
		<category><![CDATA[FRP]]></category>
		<category><![CDATA[function]]></category>
		<category><![CDATA[functional reactive programming]]></category>
		<category><![CDATA[functor]]></category>
		<category><![CDATA[monoid]]></category>
		<category><![CDATA[sequence]]></category>

		<guid isPermaLink="false">http://conal.net/blog/?p=65</guid>
		<description><![CDATA[]]></description>
			<content:encoded><![CDATA[<!-- 

Title: Sequences, streams, and segments

Tags: function, sequence, monoid, functor, applicative functor, comonad, FRP, functional reactive programming, segment

URL: http://conal.net/blog/posts/sequences-functions-and-segments/

-->

<!-- references -->

<!-- teaser -->

<p>What kind of thing is a movie?
Or a song?
Or a trajectory from point A to point B?
If you&#8217;re a computer programmer/programmee, you might say that such things are sequences of values (frames, audio samples, or spatial locations).
I&#8217;d suggest that these discrete sequences are representations of something more essential, namely a <em>flow</em> of continuously time-varying values.
Continuous models, whether in time or space, are often more compact, precise, adaptive, and composable than their discrete counterparts.</p>

<p>Functional programming offers great support for sequences of variable length.
<em>Lazy</em> functional programming adds <em>infinite</em> sequences, often called <em>streams</em>, which allows for more elegant and modular programming.</p>

<p>Functional programming also has functions as first class values, and when the function&#8217;s domain is (conceptually) continuous, we get a continuous counterpart to infinite streams.</p>

<p>Streams, sequences, and functions are three corners of a square.
Streams are discrete and infinite, sequences are discrete and finite, and functions-on-reals are continuous and infinite.
The missing corner is continuous and finite, and that corner is the topic of this post.</p>

<div align=center>
  <table border="2">
    <tr><td></td><td style="text-align:center;padding:5px"><strong>infinite</strong><td style="text-align:center;padding:5px"><strong>finite</strong></third></tr>
    <tr><td style="text-align:center;padding:5px"><strong>discrete</strong><td style="text-align:center;padding:15px">Stream</td> <td style="text-align:center;padding:15px">Sequence</td></tr>
    <tr><td style="text-align:center;padding:5px"><strong>continuous</strong><td style="text-align:center;padding:15px">Function</td> <td style="text-align:center;padding:15px"><em>???</em></td></tr>
  </table>
</div>

<p>You can download the <a href="http://conal.net/blog/code/Segment.hs">code for this post</a>.</p>

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

<ul>
<li>2008-12-01: Added <a href="http://conal.net/blog/code/Segment.hs">Segment.hs</a> link.</li>
<li>2008-12-01: Added <code>Monoid</code> instance for function segments.</li>
<li>2008-12-01: Renamed constructor &#8220;<code>DF</code>&#8221; to &#8220;<code>FS</code>&#8221; (for &#8220;function segment&#8221;)</li>
<li>2008-12-05: Tweaked the inequality in <code>mappend</code> on <code>(t :-&gt;# a)</code>. </li>
</ul>

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

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

<!--
This play has a cast of characters you may have met before.
`Monoid` is the star of the show, with `Functor` and `Applicative` playing supporting roles.
`Monad` appears only briefly.
Making her debut appearance on this blog is `Comonad`.
We'll be seeing more of her in future episodes.
-->

<h3>Streams</h3>

<p>I&#8217;ll be using Wouter Swierstra&#8217;s <a href="http://hackage.haskell.org/cgi-bin/hackage-scripts/package/Stream" title="Haskell library on Hackage">Stream library</a>.
A stream is an infinite sequence of values:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">data</span> Stream a = Cons a <span style="color: green;">&#40;</span>Stream a<span style="color: green;">&#41;</span></pre>
</div></p>

<!--, but renaming his `Cons` constructor to `(:<)`, as used in *[The Essence of Dataflow Programming][]*. -->

<p><code>Stream</code> is a functor and an applicative functor.</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="color: #833; font-weight: bold;">Functor</span></a> Stream <span style="color: #050; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>Cons x xs<span style="color: green;">&#41;</span> = Cons <span style="color: green;">&#40;</span>f x<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f xs<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#t:Applicative"><span style="color: #833; font-weight: bold;">Applicative</span></a> Stream <span style="color: #050; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a>  = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:repeat"><span style="font-weight: bold;">repeat</span></a>
    <span style="color: green;">&#40;</span>&lt;*&gt;<span style="color: green;">&#41;</span> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:zipWith"><span style="font-weight: bold;">zipWith</span></a> <span style="color: green;">&#40;</span>$<span style="color: green;">&#41;</span>
&nbsp;
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:repeat"><span style="font-weight: bold;">repeat</span></a> :: a -&gt; Stream a
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:repeat"><span style="font-weight: bold;">repeat</span></a> x = Cons x <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:repeat"><span style="font-weight: bold;">repeat</span></a> x<span style="color: green;">&#41;</span></pre>
</div></p>

<h3>Comonads</h3>

<p>Recently I&#8217;ve gotten enamored with comonads, which are dual to monads.
In other words, comonads are like monads but wearing their category arrows backwards.
I&#8217;ll be using the comonad definitions from the <a href="http://hackage.haskell.org/cgi-bin/hackage-scripts/package/category-extras" title="Haskell library on Hackage">category-extras library</a>.</p>

<p>The most helpful intuitive description I&#8217;ve found is that comonads describe <em>values in context</em>.</p>

<p>The <code>return</code> method injects a pure value into a monadic value (having no effect).</p>

<p><div>
<pre class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a>  :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="color: #833; font-weight: bold;">Monad</span></a> m     =&gt; a -&gt; m a</pre>
</div></p>

<p>The dual to monadic <code>return</code> is <code>extract</code> (sometimes called &#8220;<code>counit</code>&#8221; or &#8220;<code>coreturn</code>&#8220;), which extracts a value out of a comonadic value (discarding the value&#8217;s context).
<a href="http://hackage.haskell.org/cgi-bin/hackage-scripts/package/category-extras" title="Haskell library on Hackage">category-extras library</a> splites this method out from <code>Comonad</code> into the <code>Copointed</code> class:</p>

<p><div>
<pre class="haskell">extract :: Copointed w =&gt; w a -&gt; a</pre>
</div></p>

<p>Monadic values are typically <em>produced</em> in effectful computations:</p>

<p><div>
<pre class="haskell">a -&gt; m b</pre>
</div></p>

<p>Comonadic values are typically <em>consumed</em> in context-sensitive computations:</p>

<p><div>
<pre class="haskell">w a -&gt; b</pre>
</div></p>

<p>(Kleisli arrows wrap the producer pattern, while CoKleisli arrows wrap the consumer pattern.)</p>

<p>Monads have a way to extend a monadic producer into one that consumes to an entire monadic value:</p>

<p><div>
<pre class="haskell"><span style="color: green;">&#40;</span>=&lt;&lt;<span style="color: green;">&#41;</span> :: <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="color: #833; font-weight: bold;">Monad</span></a> m<span style="color: green;">&#41;</span> =&gt; <span style="color: green;">&#40;</span>a -&gt; m b<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>m a -&gt; m b<span style="color: green;">&#41;</span></pre>
</div></p>

<p>We more often see this operation in its flipped form (obscuring the conceptual distinction between Haskell arrows and arbitrary category arrows):</p>

<p><div>
<pre class="haskell"><span style="color: green;">&#40;</span>&gt;&gt;=<span style="color: green;">&#41;</span> :: <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="color: #833; font-weight: bold;">Monad</span></a> m<span style="color: green;">&#41;</span> =&gt; m a -&gt; <span style="color: green;">&#40;</span>a -&gt; m b<span style="color: green;">&#41;</span> -&gt; m b</pre>
</div></p>

<p>Dually, comonads have a way to extend a comonadic consumer into one that produces an entire comonadic value:</p>

<p><div>
<pre class="haskell">extend :: <span style="color: green;">&#40;</span>Comonad w<span style="color: green;">&#41;</span> =&gt; <span style="color: green;">&#40;</span>w a -&gt; b<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>w a -&gt; w b<span style="color: green;">&#41;</span></pre>
</div></p>

<p>which also has a flipped version:</p>

<p><div>
<pre class="haskell"><span style="color: green;">&#40;</span>=&gt;&gt;<span style="color: green;">&#41;</span> :: <span style="color: green;">&#40;</span>Comonad w<span style="color: green;">&#41;</span> =&gt; w a -&gt; <span style="color: green;">&#40;</span>w a -&gt; b<span style="color: green;">&#41;</span> -&gt; w b</pre>
</div></p>

<p>Another view on monads is as having a way to <code>join</code> two monadic levels into one.</p>

<p><div>
<pre class="haskell">join      :: <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="color: #833; font-weight: bold;">Monad</span></a>   m<span style="color: green;">&#41;</span> =&gt; m <span style="color: green;">&#40;</span>m a<span style="color: green;">&#41;</span> -&gt; m a</pre>
</div></p>

<p>Dually, comonads have a way to <code>duplicate</code> one level into two:</p>

<p><div>
<pre class="haskell">duplicate :: <span style="color: green;">&#40;</span>Comonad w<span style="color: green;">&#41;</span> =&gt; w a -&gt; w <span style="color: green;">&#40;</span>w a<span style="color: green;">&#41;</span></pre>
</div></p>

<p>For a monad, any of <code>join</code>, <code>(=&lt;&lt;)</code>, and <code>(&gt;&gt;=)</code> can be used to define the others.
For a comonad, any of <code>duplicate</code>, <code>extend</code>, and <code>(=&gt;&gt;)</code> can be used to define the others.</p>

<h3>The Stream comonad</h3>

<p>What might the stream comonad be?</p>

<p>The Stream library already has functions of the necessary types for <code>extract</code> and <code>duplicate</code>, corresponding to familiar list functions:</p>

<p><div>
<pre class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:head"><span style="font-weight: bold;">head</span></a> :: Stream a -&gt; a
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:head"><span style="font-weight: bold;">head</span></a> <span style="color: green;">&#40;</span>Cons x _ <span style="color: green;">&#41;</span> = x
&nbsp;
tails :: Stream a -&gt; Stream <span style="color: green;">&#40;</span>Stream a<span style="color: green;">&#41;</span>
tails xs = Cons xs <span style="color: green;">&#40;</span>tails <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:tail"><span style="font-weight: bold;">tail</span></a> xs<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre>
</div></p>

<p>where</p>

<p><div>
<pre class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:tail"><span style="font-weight: bold;">tail</span></a> :: Stream a -&gt; Stream a
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:tail"><span style="font-weight: bold;">tail</span></a> <span style="color: green;">&#40;</span>Cons _ xs<span style="color: green;">&#41;</span> = xs</pre>
</div></p>

<p>Indeed, <code>head</code> and <code>tails</code> are just what we&#8217;re looking for.</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> Copointed Stream <span style="color: #050; font-weight: bold;">where</span> extract   = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:head"><span style="font-weight: bold;">head</span></a>
<span style="color: #050; font-weight: bold;">instance</span> Comonad   Stream <span style="color: #050; font-weight: bold;">where</span> duplicate = tails</pre>
</div></p>

<p>There is also a <code>Monad</code> instance for <code>Stream</code>, in which <code>return</code> is <code>repeat</code> (matching <code>pure</code> as expected) and <code>join</code> is diagonalization, producing a stream whose <em>n<sup>th</sup></em> element is the <em>n<sup>th</sup></em> element of the <em>n<sup>th</sup></em> element of a given stream of streams.</p>

<div class="exercise">

<p><strong>Exercise</strong>: The indexing function <code>(!!)</code> is a sort of semantic function for <code>Stream</code>.
Show that <code>(!!)</code> is a morphism for <code>Functor</code>, <code>Applicative</code>, <code>Monad</code>, and <code>Comonad</code>.
In other words, the meaning of the functor is the functor of the meanings, and similarly for the other type classes.
The <code>Comonad</code> case has a little wrinkle.
See the posts on <a href="http://conal.net/blog/tag/type-class-morphism/" title="Posts on morphisms">type class morphisms</a>.</p>

</div>

<h3>Adding finiteness</h3>

<p>Lists and other possibly-finite sequence types add an interesting new aspect over streams, which is concatenation, usually wrapped in a <code>Monoid</code> instance.</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">class</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> o <span style="color: #050; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>  :: o
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a> :: o -&gt; o -&gt; o</pre>
</div></p>

<p>Lists also have <code>take</code> and <code>drop</code> operations, which can undo the effect of concatenation, as well as a notion of <code>length</code> (duration).
Let&#8217;s generalize these three to be methods of a new type class, <code>Segment</code>, so that we can defined <em>continuous</em> versions.</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">class</span> Segment seg len <span style="color: #050; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:length"><span style="font-weight: bold;">length</span></a> :: seg -&gt; len
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:drop"><span style="font-weight: bold;">drop</span></a>   :: len -&gt; seg -&gt; seg
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:take"><span style="font-weight: bold;">take</span></a>   :: len -&gt; seg -&gt; seg</pre>
</div></p>

<p>For lists, we can use the prelude functions</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> Segment <span style="color: green;">&#91;</span>a<span style="color: green;">&#93;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #833; font-weight: bold;">Int</span></a> <span style="color: #050; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:length"><span style="font-weight: bold;">length</span></a> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html"><span style="colo: #050; font-weight: bold;">Prelude</span></a>.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:length"><span style="font-weight: bold;">length</span></a>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:drop"><span style="font-weight: bold;">drop</span></a>   = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html"><span style="colo: #050; font-weight: bold;">Prelude</span></a>.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:drop"><span style="font-weight: bold;">drop</span></a>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:take"><span style="font-weight: bold;">take</span></a>   = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html"><span style="colo: #050; font-weight: bold;">Prelude</span></a>.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:take"><span style="font-weight: bold;">take</span></a></pre>
</div></p>

<p>Or the more <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-List.html#26">generic versions</a>:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Integral"><span style="color: #833; font-weight: bold;">Integral</span></a> i =&gt; Segment <span style="color: green;">&#91;</span>a<span style="color: green;">&#93;</span> i <span style="color: #050; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:length"><span style="font-weight: bold;">length</span></a> = genericLength
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:drop"><span style="font-weight: bold;">drop</span></a>   = genericDrop
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:take"><span style="font-weight: bold;">take</span></a>   = genericTake</pre>
</div></p>

<p>These three functions relate to <code>mappend</code>, to give us the following &#8220;Segment laws&#8221;:</p>

<p><div>
<pre class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:drop"><span style="font-weight: bold;">drop</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:length"><span style="font-weight: bold;">length</span></a> <span style="color: #050; font-weight: bold;">as</span><span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span><span style="color: #050; font-weight: bold;">as</span> `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` bs<span style="color: green;">&#41;</span> == bs
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:take"><span style="font-weight: bold;">take</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:length"><span style="font-weight: bold;">length</span></a> <span style="color: #050; font-weight: bold;">as</span><span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span><span style="color: #050; font-weight: bold;">as</span> `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` bs<span style="color: green;">&#41;</span> == <span style="color: #050; font-weight: bold;">as</span>
&nbsp;
t &lt;= <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:length"><span style="font-weight: bold;">length</span></a> <span style="color: #050; font-weight: bold;">as</span> ==&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:length"><span style="font-weight: bold;">length</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:take"><span style="font-weight: bold;">take</span></a> t <span style="color: #050; font-weight: bold;">as</span><span style="color: green;">&#41;</span> == t
t &lt;= <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:length"><span style="font-weight: bold;">length</span></a> <span style="color: #050; font-weight: bold;">as</span> ==&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:length"><span style="font-weight: bold;">length</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:drop"><span style="font-weight: bold;">drop</span></a> t <span style="color: #050; font-weight: bold;">as</span><span style="color: green;">&#41;</span> == <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:length"><span style="font-weight: bold;">length</span></a> <span style="color: #050; font-weight: bold;">as</span> - t</pre>
</div></p>

<h3 id="adding-continuity">Adding continuity</h3>

<p>Streams and lists are <em>discrete</em>, containing countably many or finitely many elements.
They both have <em>continuous</em> counterparts.</p>

<p>When we think of a stream as a function from natural numbers, then John Reynolds&#8217;s alternative arises: functions over <em>real numbers</em>, i.e., a continuum of values.
If we want uni-directional streams, then stick with non-negative reals.</p>

<p>Many stream and list operations are meaningful and useful not only for discrete sequences but also for their continuous counterparts.</p>

<p>The infinite (stream-like) case is already handled by the class instances for functions found in the GHC base libraries (<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Functor-Instances.html" title="Haskell module documentation">Control.Functor.Instances</a> and <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html" title="Haskell module documentation">Control.Applicative</a>).</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="color: #833; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>-&gt;<span style="color: green;">&#41;</span> t<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> = <span style="color: green;">&#40;</span>.<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#t:Applicative"><span style="color: #833; font-weight: bold;">Applicative</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>-&gt;<span style="color: green;">&#41;</span> t<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a>
    <span style="color: green;">&#40;</span>f &lt;*&gt; g<span style="color: green;">&#41;</span> x = <span style="color: green;">&#40;</span>f x<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>g x<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="color: #833; font-weight: bold;">Monad</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>-&gt;<span style="color: green;">&#41;</span> t<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a>
    f &gt;&gt;= k = \ t -&gt; k <span style="color: green;">&#40;</span>f t<span style="color: green;">&#41;</span> t</pre>
</div></p>

<p>As a consequence,</p>

<p><div>
<pre class="haskell">  join f == f &gt;&gt;= <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a> == \ t -&gt; f t t</pre>
</div></p>

<p>Assume a type wrapper, <code>NonNeg</code>, for non-negative values.
For discrete streams, <code>r == NonNeg Integer</code>, while for continuous streams, <code>r == NonNeg R</code>, for some type <code>R</code> representing reals.</p>

<p>The <a href="http://hackage.haskell.org/packages/archive/category-extras/latest/doc/html/Control-Comonad.html">co-monadic instances</a> from the <a href="http://hackage.haskell.org/cgi-bin/hackage-scripts/package/category-extras" title="Haskell library on Hackage">category-extras library</a>:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> o =&gt; Copointed <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>-&gt;<span style="color: green;">&#41;</span> o<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
    extract f = f <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>
&nbsp;
<span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> o =&gt; Comonad <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>-&gt;<span style="color: green;">&#41;</span> o<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
    duplicate f x = \ y -&gt; f <span style="color: green;">&#40;</span>x `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` y<span style="color: green;">&#41;</span></pre>
</div></p>

<h3>Finite and continuous</h3>

<p>Functions provide a setting for generalized streams.
How do we add finiteness?
A very simple answer is to combine a length (duration) with a function, to form a &#8220;function segment&#8221;:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">data</span> t :-&gt;# a = FS t <span style="color: green;">&#40;</span>t -&gt; a<span style="color: green;">&#41;</span></pre>
</div></p>

<p>The domain of this function is from zero to just short of the given length.</p>

<p>Now let&#8217;s define class instances.</p>

<p><strong>Exercise</strong>: Show that all of the instances below are semantically consistent with the <code>Stream</code> and <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#t%3AZipList"><code>ZipList</code></a> instances.</p>

<h4><code>Monoid</code></h4>

<p>Empty function segments have zero duration.
Concatenation adds durations and samples either function, right-shifting the second one.</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> t, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="color: #833; font-weight: bold;">Num</span></a> t<span style="color: green;">&#41;</span> =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#t:Monoid"><span style="color: #833; font-weight: bold;">Monoid</span></a> <span style="color: green;">&#40;</span>t :-&gt;# a<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a> = FS <span style="color: red;">0</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:error"><span style="font-weight: bold;">error</span></a> <span style="color: green;">&quot;sampling empty 't :-&gt;# a'&quot;</span><span style="color: green;">&#41;</span>
    FS c f `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` FS d g =
      FS <span style="color: green;">&#40;</span>c + d<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>\ t -&gt; <span style="color: #050; font-weight: bold;">if</span> t &lt;= c <span style="color: #050; font-weight: bold;">then</span> f t <span style="color: #050; font-weight: bold;">else</span> g <span style="color: green;">&#40;</span>t - c<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre>
</div></p>

<h4><code>Segment</code></h4>

<p>The <code>Segment</code> operations are easy to define:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="color: #833; font-weight: bold;">Num</span></a> t =&gt; Segment <span style="color: green;">&#40;</span>t :-&gt;# a<span style="color: green;">&#41;</span> t <span style="color: #050; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:length"><span style="font-weight: bold;">length</span></a> <span style="color: green;">&#40;</span>FS d _<span style="color: green;">&#41;</span> = d
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:drop"><span style="font-weight: bold;">drop</span></a> t <span style="color: green;">&#40;</span>FS d f<span style="color: green;">&#41;</span> = FS <span style="color: green;">&#40;</span>d - t<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>\ t' -&gt; f <span style="color: green;">&#40;</span>t + t'<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:take"><span style="font-weight: bold;">take</span></a> t <span style="color: green;">&#40;</span>FS _ f<span style="color: green;">&#41;</span> = FS t f</pre>
</div></p>

<p>Notice what&#8217;s going on with <code>drop</code>.
The length gets shortened by <code>t</code> (the amount dropped), and the function gets shifted (to the &#8220;left&#8221;) by <code>t</code>.</p>

<p>There&#8217;s also a tantalizing resemblance between this <code>drop</code> definition and <code>duplicate</code> for the function comonad.
We&#8217;ll return in another post to tease out this and</p>

<p>I&#8217;ve allowed dropping or taking more than is present, though these cases can be handled with an error or a by taking or dropping fewer elements (as with the list <code>drop</code> and <code>take</code> functions).</p>

<h4><code>Functor</code>, <code>Zip</code> and <code>Applicative</code></h4>

<p><code>fmap</code> applies a given function to each of the function values, leaving the length unchanged.</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="color: #833; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>:-&gt;#<span style="color: green;">&#41;</span> t<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> h <span style="color: green;">&#40;</span>FS d f<span style="color: green;">&#41;</span> = FS d <span style="color: green;">&#40;</span>h . f<span style="color: green;">&#41;</span></pre>
</div></p>

<p><code>zip</code> pairs corresponding segment values and runs out with the shorter segment.
(See <em><a href="http://conal.net/blog/posts/more-beautiful-fold-zipping" title="blog post">More beautiful fold zipping</a></em> for the <code>Zip</code> class.)</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> t =&gt; Zip <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>:-&gt;#<span style="color: green;">&#41;</span> t<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
    FS xd xf `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:zip"><span style="font-weight: bold;">zip</span></a>` FS yd yf = FS <span style="color: green;">&#40;</span>xd `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:min"><span style="font-weight: bold;">min</span></a>` yd<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>xf `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:zip"><span style="font-weight: bold;">zip</span></a>` yf<span style="color: green;">&#41;</span></pre>
</div></p>

<p><code>pure</code> produces a constant value going forever.
<code>(&lt;*&gt;)</code> applies functions to corresponding arguments, running out with the shorter.</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="color: #833; font-weight: bold;">Ord</span></a> t, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bounded"><span style="color: #833; font-weight: bold;">Bounded</span></a> t<span style="color: green;">&#41;</span> =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#t:Applicative"><span style="color: #833; font-weight: bold;">Applicative</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>:-&gt;#<span style="color: green;">&#41;</span> t<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a> a = FS <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:maxBound"><span style="font-weight: bold;">maxBound</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a> a<span style="color: green;">&#41;</span>
    <span style="color: green;">&#40;</span>&lt;*&gt;<span style="color: green;">&#41;</span>  = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:zipWith"><span style="font-weight: bold;">zipWith</span></a> <span style="color: green;">&#40;</span>$<span style="color: green;">&#41;</span></pre>
</div></p>

<h4><code>Copointed</code> and <code>Comonad</code></h4>

<p><code>extract</code> pulls out the initial value (like <code>head</code>).</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="color: #833; font-weight: bold;">Num</span></a> t =&gt; Copointed <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>:-&gt;#<span style="color: green;">&#41;</span> t<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
    extract <span style="color: green;">&#40;</span>FS _ f<span style="color: green;">&#41;</span> = f <span style="color: red;">0</span></pre>
</div></p>

<p><code>duplicate</code> acts like <code>tails</code>.
The generated segments are progressivly <code>drop</code>ped versions of the original segment.</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="color: #833; font-weight: bold;">Num</span></a> t =&gt; Comonad <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>:-&gt;#<span style="color: green;">&#41;</span> t<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
    duplicate s = FS <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:length"><span style="font-weight: bold;">length</span></a> s<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:flip"><span style="font-weight: bold;">flip</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:drop"><span style="font-weight: bold;">drop</span></a> s<span style="color: green;">&#41;</span></pre>
</div></p>

<h4><code>Monad</code></h4>

<p>I don&#8217;t know if there is a monad instance for <code>((:-&gt;#) t)</code>.
Simple diagonalization doesn&#8217;t work for <code>join</code>, since the <em>n<sup>th</sup></em> segment might be shorter than <em>n</em>.</p>

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

<p>The instances above remind me strongly of type class instances for several common types.
Another post will tease out some patterns and reconstruct <code>(t :-&gt;# a)</code> out of standard components, so that most of the code above can disappear.</p>

<p>Another post incorporates <code>(t :-&gt;# a)</code> into a new model and implementation of relative-time, comonadic FRP.</p>
]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/sequences-streams-and-segments/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Early inspirations and new directions in functional reactive programming</title>
		<link>http://conal.net/blog/posts/early-inspirations-and-new-directions-in-functional-reactive-programming/</link>
		<comments>http://conal.net/blog/posts/early-inspirations-and-new-directions-in-functional-reactive-programming/#comments</comments>
		<pubDate>Mon, 01 Dec 2008 07:24:09 +0000</pubDate>
		<dc:creator>conal</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[FRP]]></category>
		<category><![CDATA[functional reactive programming]]></category>
		<category><![CDATA[history]]></category>
		<category><![CDATA[inspiration]]></category>
		<category><![CDATA[relative time]]></category>

		<guid isPermaLink="false">http://conal.net/blog/?p=66</guid>
		<description><![CDATA[]]></description>
			<content:encoded><![CDATA[<!-- 

Title: Early inspirations and new directions in functional reactive programming

Tags: history, inspiration, relative time, FRP, functional reactive programming

URL: http://conal.net/blog/posts/early-inspirations-and-new-directions-in-functional-reactive-programming/

-->

<!-- references -->

<!-- teaser -->

<p>In 1989, I was a grad student nearing completion at Carnegie Mellon.
Kavi Arya gave a talk on &#8220;functional animation&#8221;, using lazy lists.
I was awe-struck with the elegance and power of that simple idea, and I&#8217;ve been hooked on functional animation ever since.</p>

<p>At the end of Kavi&#8217;s talk, <a href="http://www.cs.cmu.edu/~jcr/">John Reynolds</a> offered a remark, roughly as follows:</p>

<blockquote>
  <p>You can think of sequences as functions from the natural numbers.
  Have you thought about functions from the reals instead?
  Doing so might help with the awkwardness with interpolation.</p>
</blockquote>

<p>I knew at once I&#8217;d heard a wonderful idea, so I went back to my office, wrote it down, and promised myself that I wouldn&#8217;t think about Kavi&#8217;s work and John&#8217;s insight until my dissertation was done.
Otherwise, I might never have finished.
A year or so later, at Sun Microsystems, I started working on functional animation, which then grew into functional reactive programming (FRP).</p>

<p>In the dozens of variations on FRP I&#8217;ve played with over the last 15 years, John&#8217;s refinement of Kavi&#8217;s idea has always been the heart of the matter for me.</p>

<p>Lately, I&#8217;ve been rethinking FRP yet again, and I&#8217;m very excited about where it&#8217;s leading me.</p>

<p>The semantic model of FRP has been based on behaviors of infinite duration and, mostly on absolute time.
Recently I realized that some problems of non-modular interaction could be elegantly addressed by switching to finite duration and relative time, and by adopting a <em>co-monadic</em> approach.</p>

<p>Upcoming post will explore these ideas.</p>

<!--
**Edits**:

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

<!-- without a comment or something here, the last item above becomes a paragraph -->
]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/early-inspirations-and-new-directions-in-functional-reactive-programming/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Simplifying semantics with type class morphisms</title>
		<link>http://conal.net/blog/posts/simplifying-semantics-with-type-class-morphisms/</link>
		<comments>http://conal.net/blog/posts/simplifying-semantics-with-type-class-morphisms/#comments</comments>
		<pubDate>Wed, 09 Apr 2008 04:22:35 +0000</pubDate>
		<dc:creator>conal</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[applicative functor]]></category>
		<category><![CDATA[FRP]]></category>
		<category><![CDATA[functional reactive programming]]></category>
		<category><![CDATA[functor]]></category>
		<category><![CDATA[monad]]></category>
		<category><![CDATA[monoid]]></category>
		<category><![CDATA[semantics]]></category>
		<category><![CDATA[type class]]></category>
		<category><![CDATA[type class morphism]]></category>

		<guid isPermaLink="false">http://conal.net/blog/?p=23</guid>
		<description><![CDATA[]]></description>
			<content:encoded><![CDATA[<!-- 

Title: Simplifying semantics with type class morphisms

Tags: type class, functor, applicative functor, monad, monoid, type class morphism, semantics, FRP, functional reactive programming

URL: http://conal.net/blog/posts/simplifying-semantics-with-type-class-morphisms

-->

<!-- references -->

<!-- teaser -->

<p>When I first started playing with functional reactivity in Fran and its predecessors, I didn&#8217;t realize that much of the functionality of events and reactive behaviors could be packaged via standard type classes.
Then Conor McBride &amp; Ross Paterson introduced us to <em><a href="http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html" title="Documentation for Control.Applicative: applicative functors">applicative functors</a></em>, and I remembered using that pattern to reduce all of the lifting operators in Fran to just two, which correspond to <code>pure</code> and <code>(&lt;*&gt;)</code> in the <code>Applicative</code> class.
So, in working on a new library for functional reactive programming (FRP), I thought I&#8217;d modernize the interface to use standard type classes as much as possible.</p>

<p>While spelling out a precise (denotational) semantics for the FRP instances of these classes, I noticed a lovely recurring pattern:</p>

<blockquote>
  <p>The meaning of each method corresponds to the same method for the meaning.</p>
</blockquote>

<p>In this post, I&#8217;ll give some examples of this principle and muse a bit over its usefulness.
For more details, see the paper <em><a href="http://conal.net/blog/posts/simply-efficient-functional-reactivity/" title="Blog post: &quot;Simply efficient functional reactivity&quot;">Simply efficient functional reactivity</a></em>.
Another post will start exploring type class morphisms and type composition, and ask questions I&#8217;m wondering about.</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-23"></span></p>

<h3>Behaviors</h3>

<p>The meaning of a (reactive) behavior is a function from time:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">type</span> B a = Time -&gt; a
&nbsp;
at :: Behavior a -&gt; B a</pre>
</div></p>

<p>So the semantic function, <code>at</code>, maps from the <code>Behavior</code> type (for use in FRP programs) to the <code>B</code> type (for understanding FRP programs)</p>

<p>As a simple example, the meaning of the behavior <code>time</code> is the identity function:</p>

<p><div>
<pre class="haskell">at time == <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a></pre>
</div></p>

<h4>Functor</h4>

<p>Given <code>b :: Behavior a</code> and a function <code>f :: a -&gt; b</code>, we can apply <code>f</code> to the value of <code>b</code> at every moment in (infinite and continuous) time.
This operation corresponds to the <code>Functor</code> method <code>fmap</code>, so</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="color: #833; font-weight: bold;">Functor</span></a> Behavior <span style="color: #050; font-weight: bold;">where</span> ...</pre>
</div></p>

<p>The informal description of <code>fmap</code> on behavior translates to a formal definition of its semantics:</p>

<p><div>
<pre class="haskell">  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f b `at` t == f <span style="color: green;">&#40;</span>b `at` t<span style="color: green;">&#41;</span></pre>
</div></p>

<p>Equivalently,</p>

<p><div>
<pre class="haskell">  at <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f b<span style="color: green;">&#41;</span> == \ t -&gt; f <span style="color: green;">&#40;</span>b `at` t<span style="color: green;">&#41;</span>
                == f . <span style="color: green;">&#40;</span>\ t -&gt; b `at` t<span style="color: green;">&#41;</span>
                == f . at b</pre>
</div></p>

<p>Now here&#8217;s the fun part.
While <code>Behavior</code> is a functor, <em>so is its meaning</em>:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="color: #833; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>-&gt;<span style="color: green;">&#41;</span> t<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> = <span style="color: green;">&#40;</span>.<span style="color: green;">&#41;</span></pre>
</div></p>

<p>So, replacing <code>f . at b</code> with <code>fmap f (at b)</code> above,</p>

<p><div>
<pre class="haskell">  at <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f b<span style="color: green;">&#41;</span> == <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>at b<span style="color: green;">&#41;</span></pre>
</div></p>

<p>which can also be written</p>

<p><div>
<pre class="haskell">  at . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f == <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f . at</pre>
</div></p>

<p>Keep in mind here than the <code>fmap</code> on the left is on behaviors, and on the right is functions (of time).</p>

<p>This last equation can also be written as a simple square commutative diagram and is sometimes expressed by saying that <code>at</code> is a &#8220;natural transformation&#8221; or &#8220;morphism on functors&#8221; [<a href="http://books.google.com/books?id=eBvhyc4z8HQC" title="Book: &quot;Categories for the Working Mathematician&quot; by Saunders Mac Lane">Categories for the Working Mathematician</a>].
For consistency with similar properties on other type classes, I suggest &#8220;functor morphism&#8221; as a synonym for natural transformation.</p>

<p>The <a href="http://www.haskell.org/haskellwiki/Category_theory/Natural_transformation" title="Haskell wiki page: &quot;Haskell wiki page on natural transformations&quot;">Haskell wiki page on natural transformations</a> shows the commutative diagram and gives <code>maybeToList</code> as another example.</p>

<h4>Applicative functor</h4>

<p>The <code>fmap</code> method applies a static (not time-varying) function to a dynamic (time-varying) argument.
A more general operation applies a dynamic function to a dynamic argument.
Also useful is promoting a static value to a dynamic one.
These two operations correspond to <code>(&lt;*&gt;)</code> and <code>pure</code> for <a href="http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html" title="Documentation for Control.Applicative: applicative functors">applicative functors</a>:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">infixl</span> <span style="color: red;">4</span> &lt;*&gt;
<span style="color: #050; font-weight: bold;">class</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="color: #833; font-weight: bold;">Functor</span></a> f =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#t:Applicative"><span style="color: #833; font-weight: bold;">Applicative</span></a> f <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a>  :: a -&gt; f a
  <span style="color: green;">&#40;</span>&lt;*&gt;<span style="color: green;">&#41;</span> :: f <span style="color: green;">&#40;</span>a-&gt;b<span style="color: green;">&#41;</span> -&gt; f a -&gt; f b</pre>
</div></p>

<p>where, e.g., <code>f == Behavior</code>.</p>

<p>From these two methods, all of the n-ary lifting functions follow.
For instance,</p>

<p><div>
<pre class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:liftA3"><span style="font-weight: bold;">liftA3</span></a> :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#t:Applicative"><span style="color: #833; font-weight: bold;">Applicative</span></a> f =&gt;
          <span style="color: green;">&#40;</span>  a -&gt;   b -&gt;   c -&gt;   d<span style="color: green;">&#41;</span>
       -&gt;  f a -&gt; f b -&gt; f c -&gt; f d
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:liftA3"><span style="font-weight: bold;">liftA3</span></a> h fa fb fc = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a> h &lt;*&gt; fa &lt;*&gt; fb &lt;*&gt; fc</pre>
</div></p>

<p>Or use <code>fmap h fa</code> in place of <code>pure h &lt;*&gt; fa</code>.
For prettier code, <code>(&lt;$&gt;)</code> (left infix) is synonymous with <code>fmap</code>.</p>

<p>Now, what about semantics?
Applying a dynamic function <code>fb</code> to a dynamic argument <code>xb</code> gives a dynamic result, whose value at time <code>t</code> is the value of <code>fb</code> at <code>t</code>, applied to the value of <code>xb</code> at <code>t</code>.</p>

<p><div>
<pre class="haskell">at <span style="color: green;">&#40;</span>fb &lt;*&gt; xb<span style="color: green;">&#41;</span> == \ t -&gt; <span style="color: green;">&#40;</span>fb `at` t<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>xb `at` t<span style="color: green;">&#41;</span></pre>
</div></p>

<p>The <code>(&lt;*&gt;)</code> operator is the heart of FRP&#8217;s concurrency model, which is determinate, synchronous, and continuous.</p>

<p>Promoting a static value yields a constant behavior:</p>

<p><div>
<pre class="haskell">at <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a> a<span style="color: green;">&#41;</span> == \ t -&gt; a
            == <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a> a</pre>
</div></p>

<p>As with <code>Functor</code>, let&#8217;s look at the <code>Applicative</code> instance of functions (the meaning of behaviors):</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#t:Applicative"><span style="color: #833; font-weight: bold;">Applicative</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>-&gt;<span style="color: green;">&#41;</span> t<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a> a    = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a> a
  hf &lt;*&gt; xf = \ t -&gt; <span style="color: green;">&#40;</span>hf t<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>xf t<span style="color: green;">&#41;</span></pre>
</div></p>

<p>Wow &#8212; these two definitions look a lot like the meanings given above for <code>pure</code> and <code>(&lt;*&gt;)</code> on behaviors.
And sure enough, we can use the function instance to simplify these semantic definitions:</p>

<p><div>
<pre class="haskell">at <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a> a<span style="color: green;">&#41;</span>    == <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a> a
at <span style="color: green;">&#40;</span>fb &lt;*&gt; xb<span style="color: green;">&#41;</span> == at fb &lt;*&gt; at xb</pre>
</div></p>

<p>Thus the semantic function distributes over the <code>Applicative</code> methods.
In other words, the meaning of each method is the method on the meaning.
I don&#8217;t know of any standard term (like &#8220;natural transformation&#8221;) for this relationship between <code>at</code> and <code>pure</code>/<code>(&lt;*&gt;)</code>.
I suggest calling <code>at</code> an &#8220;applicative functor morphism&#8221;.</p>

<h4>Monad</h4>

<p>Monad morphisms are a bit trickier, due to the types.
There are two equivalent forms of the definition of a monad morphism, depending on whether you use <code>join</code> or <code>(&gt;&gt;=)</code>.
In the <code>join</code> form (e.g., in <a href="http://citeseer.ist.psu.edu/wadler92comprehending.html" title="Paper: &quot;Comprehending Monads&quot;">Comprehending Monads</a>, section 6), for monads <code>m</code> and <code>n</code>, the function <code>nu :: forall a. m a -&gt; n a</code> is a monad morphism if</p>

<p><div>
<pre class="haskell">nu . join == join . nu . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> nu</pre>
</div></p>

<p>where</p>

<p><div>
<pre class="haskell">join :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="color: #833; font-weight: bold;">Monad</span></a> m =&gt; m <span style="color: green;">&#40;</span>m a<span style="color: green;">&#41;</span> -&gt; m a</pre>
</div></p>

<p>For behavior semantics, <code>m == Behavior</code>, <code>n == B == (-&gt;) Time</code>, and <code>nu == at</code>.</p>

<p>Then <code>at</code> is also a monad morphism if</p>

<p><div>
<pre class="haskell">at <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> a<span style="color: green;">&#41;</span> == <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> a
at <span style="color: green;">&#40;</span>join bb<span style="color: green;">&#41;</span>  == join <span style="color: green;">&#40;</span>at <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> at bb<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre>
</div></p>

<p>And, since for functions <code>f</code>,</p>

<p><div>
<pre class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> h f == h . f
join f   == \ t -&gt; f t t</pre>
</div></p>

<p>the second condition is</p>

<p><div>
<pre class="haskell">at <span style="color: green;">&#40;</span>join bb<span style="color: green;">&#41;</span> == join <span style="color: green;">&#40;</span>at <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> at bb<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
             == \ t -&gt; at <span style="color: green;">&#40;</span>at . bb<span style="color: green;">&#41;</span> t t
             == \ t -&gt; at <span style="color: green;">&#40;</span>at bb t<span style="color: green;">&#41;</span> t
             == \ t -&gt; <span style="color: green;">&#40;</span>bb `at` t<span style="color: green;">&#41;</span> `at` t</pre>
</div></p>

<p>So sampling <code>join bb</code> at <code>t</code> means sampling <code>bb</code> at <code>t</code> to get a behavior <code>b</code>, which is also sampled at <code>t</code>.
That&#8217;s exactly what I&#8217;d guess <code>join</code> to mean on behaviors.</p>

<p><em>Note:</em> the FRP implementation described in <em><a href="http://conal.net/blog/posts/simply-efficient-functional-reactivity/" title="Blog post: &quot;Simply efficient functional reactivity&quot;">Simply efficient functional reactivity</a></em> <em>does not</em> include a <code>Monad</code> instance for <code>Behavior</code>, because I don&#8217;t see how to implement one with the hybrid data-/demand-driven <code>Behavior</code> implementation.
However, the closely related but less expressive type, <code>Reactive</code>, has the same semantic model as <code>Behavior</code>.  <code>Reactive</code> does have a Monad instance, and its semantic function (<code>rats</code>) <em>is</em> a monad morphism.</p>

<h4>Other examples</h4>

<p><a href="http://conal.net/blog/posts/simply-efficient-functional-reactivity/" title="Blog post: &quot;Simply efficient functional reactivity&quot;">The <em>Simply</em> paper</a> contains several more examples of type class morphisms:</p>

<ul>
<li><a href="http://conal.net/blog/posts/reactive-values-from-the-future/" title="Blog post: &quot;Reactive values from the future&quot;">Reactive values</a>, time functions, and <a href="http://conal.net/blog/posts/future-values/" title="Blog post: &quot;Future values&quot;">future values</a> are also morphisms on <code>Functor</code>, <code>Applicative</code>, and <code>Monad</code>.</li>
<li><em>Improving values</em> are morphisms on <code>Ord</code>.</li>
</ul>

<p>The paper also includes a significant <em>non-example</em>, namely events.
The semantics I gave for <code>Event a</code> is a time-ordered list of time/value pairs.  However, the semantic function (<code>occs</code>) <em>is not</em> a <code>Monoid</code> morphism, because</p>

<p><div>
<pre class="haskell">occs <span style="color: green;">&#40;</span>e `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` e'<span style="color: green;">&#41;</span> == occs e `merge` occs e'</pre>
</div></p>

<p>and <code>merge</code> is not <code>(++)</code>, which is <code>mappend</code> on lists.</p>

<h4>Why care about type class morphisms?</h4>

<p>I want my library&#8217;s users to think of behaviors and future values as being their semantic models (functions of time and time/value pairs).
Why?
Because these denotational models are simple and precise and have simple and useful formal properties.
Those properties allow library users to program with confidence, and allow library providers to make radical changes in representation and implementation (even from demand-driven to data-driven) without breaking client programs.</p>

<p>When I think of a behavior as a function of time, I&#8217;d like it to act like a function of time, hence <code>Functor</code>, <code>Applicative</code>, and <code>Monad</code>.
And if it does implement any classes in common with functions, then it had better agree the function instances of those classes.
Otherwise, user expectations will be mistaken, and the illusion is broken.</p>

<p>I&#8217;d love to hear about other examples of type class morphisms, particularly for <code>Applicative</code> and <code>Monad</code>, as well as thoughts on their usefulness.</p>
]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/simplifying-semantics-with-type-class-morphisms/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Simply efficient functional reactivity</title>
		<link>http://conal.net/blog/posts/simply-efficient-functional-reactivity/</link>
		<comments>http://conal.net/blog/posts/simply-efficient-functional-reactivity/#comments</comments>
		<pubDate>Fri, 04 Apr 2008 22:27:43 +0000</pubDate>
		<dc:creator>conal</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[applicative functor]]></category>
		<category><![CDATA[continuous]]></category>
		<category><![CDATA[discrete]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[FRP]]></category>
		<category><![CDATA[functional reactive programming]]></category>
		<category><![CDATA[functor]]></category>
		<category><![CDATA[future value]]></category>
		<category><![CDATA[icfp]]></category>
		<category><![CDATA[implementation]]></category>
		<category><![CDATA[joinMaybes]]></category>
		<category><![CDATA[monad]]></category>
		<category><![CDATA[monoid]]></category>
		<category><![CDATA[multi-threading]]></category>
		<category><![CDATA[normal form]]></category>
		<category><![CDATA[paper]]></category>
		<category><![CDATA[reactive behavior]]></category>
		<category><![CDATA[reactive value]]></category>
		<category><![CDATA[semantics]]></category>
		<category><![CDATA[time]]></category>
		<category><![CDATA[type class]]></category>
		<category><![CDATA[type class morphism]]></category>
		<category><![CDATA[type composition]]></category>

		<guid isPermaLink="false">http://conal.net/blog/posts/simply-efficient-functional-reactivity/</guid>
		<description><![CDATA[]]></description>
			<content:encoded><![CDATA[<!-- 

Title: Simply efficient functional reactivity

Tags: applicative functor, continuous, discrete, event, FRP, functional reactive programming, functor, future value, icfp, implementation, joinMaybes, monad, monoid, type class morphism, multi-threading, normal form, paper, reactive behavior, reactive value, semantics, time, type class, type composition

URL: http://conal.net/blog/posts/simply-efficient-functional-reactivity/

-->

<!-- references -->

<!-- teaser -->

<p>I submitted a paper <em><a href="http://conal.net/papers/simply-reactive" title="Paper: &quot;Simply efficient functional reactivity&quot;">Simply efficient functional reactivity</a></em> to <a href="http://www.icfpconference.org/icfp2008" title="ICFP 2008 conference page">ICFP 2008</a>.</p>

<p><strong>Abstract:</strong></p>

<blockquote>
  <p>Functional reactive programming (FRP) has simple and powerful semantics, but has resisted efficient implementation.  In particular, most past implementations have used demand-driven sampling, which accommodates FRP&#8217;s continuous time semantics and fits well with the nature of functional programming.  Consequently, values are wastefully recomputed even when inputs don&#8217;t change, and reaction latency can be as high as the sampling period.</p>
  
  <p>This paper presents a way to implement FRP that combines data- and demand-driven evaluation, in which values are recomputed only when necessary, and reactions are nearly instantaneous.  The implementation is rooted in a new simple formulation of FRP and its semantics and so is easy to understand and reason about.</p>
  
  <p>On the road to efficiency and simplicity, we&#8217;ll meet some old friends (monoids, functors, applicative functors, monads, morphisms, and improving values) and make some new friends (functional future values, reactive normal form, and concurrent &#8220;unambiguous choice&#8221;).</p>
</blockquote>

<!--
**Edits**:

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

<!-- without a comment or something here, the last item above becomes a paragraph -->
]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/simply-efficient-functional-reactivity/feed/</wfw:commentRss>
		<slash:comments>33</slash:comments>
		</item>
		<item>
		<title>Pairs, sums, and reactivity</title>
		<link>http://conal.net/blog/posts/pairs-sums-and-reactivity/</link>
		<comments>http://conal.net/blog/posts/pairs-sums-and-reactivity/#comments</comments>
		<pubDate>Mon, 18 Feb 2008 05:40:31 +0000</pubDate>
		<dc:creator>conal</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[FRP]]></category>
		<category><![CDATA[functional reactive programming]]></category>

		<guid isPermaLink="false">http://conal.net/blog/posts/pairs-sums-and-reactivity/</guid>
		<description><![CDATA[]]></description>
			<content:encoded><![CDATA[<!-- 

Title: Pairs, sums, and reactivity

Tags: functional reactive programming, FRP

-->

<!-- references -->

<!-- teaser -->

<p>I&#8217;ve been noodling over a difference between behaviors (functions of time) and events (sequences of time/value pairs).  A product of behaviors is isomorphic to a behavior of products, but a product of events is isomorphic to an event of <em>sums</em>.</p>

<p><div class=latex><img src='http://conal.net/blog/wp-content/latex/416/4162edc9d5f3898055ee4b050ac73e3a-ffffff000000.png' alt='B_a \times B_b \cong B_{a \times b}' class='latex' /></div>
<div class=latex><img src='http://conal.net/blog/wp-content/latex/96c/96c9316d106371d30febcf90ab328610-ffffff000000.png' alt='E_a \times E_b \cong E_{a + b}' class='latex' /></div></p>

<p>A similar property has been noted for Fudgets-like stream processors.</p>

<p>Behaviors (or &#8220;<a href="http://conal.net/blog/posts/reactive-values-from-the-future/" title="Blog post: &quot;Reactive values from the future&quot;">reactive values</a>&#8220;) and events are inter-related.  In particular, we can make a behavior from an initial value and an event, using the <code>stepper</code> function.  If we want to use <code>stepper</code> with a pair value, we&#8217;d have to use a pair-valued event.  However, it&#8217;s often more convenient and efficient to work with pair of separate change events, or (using the event pair/sum isomorphism) a sum-valued event.</p>

<p>This post plays with another perspective on sum types for events and stream processors.  It can also apply to <a href="http://conal.net/blog/tag/bot/" title="Blog articles tagged &quot;bot&quot;">bot</a>s.</p>

<!--
*Edit 2008-02-09*: just fiddling around
-->

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

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

<h3>Pairs and sums</h3>

<p>Let&#8217;s take a look at the event pair/sum isomorphism.  To mix two events into a single sum event, simply left- or right-tag the events and merge them:</p>

<p><div>
<pre class="haskell">mixEither   :: <span style="color: green;">&#40;</span>Event c, Event d<span style="color: green;">&#41;</span> -&gt; Event <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="color: #833; font-weight: bold;">Either</span></a> c d<span style="color: green;">&#41;</span>
mixEither <span style="color: green;">&#40;</span>ec,ed<span style="color: green;">&#41;</span> = liftM Left ec `mplus` liftM Right ed</pre>
</div></p>

<p>In this definition, I could have used <code>fmap</code> in place of <code>liftM</code> and/or <code>mappend</code> in place of <code>mplus</code>.  We&#8217;ll see in a moment that <code>liftM</code> and <code>mplus</code> give a nicer symmetry.</p>

<p>To separate a sum event into two, use <a href="http://conal.net/blog/posts/a-handy-generalized-filter/" title="Blog post: &quot;A handy generalized filter&quot;"><code>joinMaybes</code></a>.</p>

<p><div>
<pre class="haskell">joinMaybes :: MonadPlus m =&gt; m <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Maybe"><span style="color: #833; font-weight: bold;">Maybe</span></a> a<span style="color: green;">&#41;</span> -&gt; m a
&nbsp;
unmixEither :: Event <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="color: #833; font-weight: bold;">Either</span></a> c d<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>Event c, Event d<span style="color: green;">&#41;</span>
unmixEither ecd = <span style="color: green;">&#40;</span>filt <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Arrow.html#v:left"><span style="font-weight: bold;">left</span></a>, filt <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Arrow.html#v:right"><span style="font-weight: bold;">right</span></a><span style="color: green;">&#41;</span>
 <span style="color: #050; font-weight: bold;">where</span>
   filt f = joinMaybes <span style="color: green;">&#40;</span>liftM f ecd<span style="color: green;">&#41;</span></pre>
</div></p>

<p>The functions <code>left</code> and <code>right</code> are <code>Maybe</code>-valued extractors for sum types.</p>

<p><div>
<pre class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Arrow.html#v:left"><span style="font-weight: bold;">left</span></a>  :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="color: #833; font-weight: bold;">Either</span></a> c d -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Maybe"><span style="color: #833; font-weight: bold;">Maybe</span></a> c
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Arrow.html#v:right"><span style="font-weight: bold;">right</span></a> :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="color: #833; font-weight: bold;">Either</span></a> c d -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Maybe"><span style="color: #833; font-weight: bold;">Maybe</span></a> d</pre>
</div></p>

<p>The mixer and unmixer actually have much more general types:</p>

<p><div>
<pre class="haskell">mixEither   :: MonadPlus m =&gt; <span style="color: green;">&#40;</span>m a, m b<span style="color: green;">&#41;</span> -&gt; m <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="color: #833; font-weight: bold;">Either</span></a> a b<span style="color: green;">&#41;</span>
&nbsp;
unmixEither :: MonadPlus m =&gt; m <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="color: #833; font-weight: bold;">Either</span></a> c d<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>m c, m d<span style="color: green;">&#41;</span></pre>
</div></p>

<p>The simplicity and symmetry these typings motivated my choice of <code>liftM</code> and <code>mplus</code> above.</p>

<p>In this more general setting, <code>mixEither . unmixEither</code> might not be the identity.  For lists, all of the lefts will end up before all of the rights.  Even for events, <code>mixEither . unmixEither</code> can re-order simultaneous occurrences.  I don&#8217;t know how to get a genuine isomorphism.</p>

<h3>Pair editors</h3>

<p>When using <code>stepper</code>, the event argument indicates a <em>change</em> to the varying value.  When the varying value is a pair, we&#8217;ll often have change events for each pair member.  Let&#8217;s see how to weave those two events into a single pair-valued event.</p>

<p>The pair/sum isomorphism above says that a pair of events is equivalent to a sum-valued event.  But what do we do with the sum event?  The key idea is noted in <a href="http://conal.net/blog/posts/functional-reactive-partner-dancing/" title="Blog post: &quot;Functional reactive partner dancing&quot;">Functional reactive partner dancing</a>: convert the sum into a <em>pair editor</em>:</p>

<p><div>
<pre class="haskell">updPair :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="color: #833; font-weight: bold;">Either</span></a> c d -&gt; <span style="color: green;">&#40;</span>c,d<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>c,d<span style="color: green;">&#41;</span>
&nbsp;
updPair <span style="color: green;">&#40;</span>Left  c'<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>_,d<span style="color: green;">&#41;</span> = <span style="color: green;">&#40;</span>c',d<span style="color: green;">&#41;</span>
updPair <span style="color: green;">&#40;</span>Right d'<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>c,_<span style="color: green;">&#41;</span> = <span style="color: green;">&#40;</span>c,d'<span style="color: green;">&#41;</span></pre>
</div></p>

<p>Equivalently,</p>

<p><div>
<pre class="haskell">updPair = <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Arrow.html#v:first"><span style="font-weight: bold;">first</span></a>.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a><span style="color: green;">&#41;</span> `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:either"><span style="font-weight: bold;">either</span></a>` <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Arrow.html#v:second"><span style="font-weight: bold;">second</span></a>.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a><span style="color: green;">&#41;</span></pre>
</div></p>

<p>Now we can go from a pair of events to an event of <em>pair editors</em>:</p>

<p><div>
<pre class="haskell">pairEditE :: <span style="color: green;">&#40;</span>Event c, Event d<span style="color: green;">&#41;</span> -&gt; Event <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>c,d<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>c,d<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
pairEditE = liftM updPair . mixEither</pre>
</div></p>

<p>If we want, we can also short-cut the whole sum business:</p>

<p><div>
<pre class="haskell">pairEditE <span style="color: green;">&#40;</span>ce,de<span style="color: green;">&#41;</span> =
  liftM <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Arrow.html#v:first"><span style="font-weight: bold;">first</span></a>.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a><span style="color: green;">&#41;</span> ce `mplus` liftM <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Arrow.html#v:second"><span style="font-weight: bold;">second</span></a>.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a><span style="color: green;">&#41;</span> de</pre>
</div></p>

<p>With either of these definitions, we have a much more general type:</p>

<p><div>
<pre class="haskell">pairEditE :: MonadPlus m =&gt; <span style="color: green;">&#40;</span>m c,m d<span style="color: green;">&#41;</span> -&gt; m <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>c,d<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>c,d<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre>
</div></p>

<p>The next step is to apply successive functions from the pair-changing event, using an accumulation combinator.  We&#8217;ll need an initial value for the pair:</p>

<p><div>
<pre class="haskell">pairE :: <span style="color: green;">&#40;</span>c,d<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>Event c, Event d<span style="color: green;">&#41;</span> -&gt; Event <span style="color: green;">&#40;</span>c,d<span style="color: green;">&#41;</span>
cd `pairE` cde = cd `accumE` pairEditE cde</pre>
</div></p>

<p>There&#8217;s another way to dice up <code>pairE</code>.  A reactive value is determined by an initial value and change event, so we can restructure the arguments of <code>pairE</code> into two reactive values.  We also have an initial value for the combination, so we may as well produce a reactive value.</p>

<p><div>
<pre class="haskell">pairR :: Reactive c -&gt; Reactive d -&gt; Reactive <span style="color: green;">&#40;</span>c,d<span style="color: green;">&#41;</span>
<span style="color: green;">&#40;</span>c `Stepper` ce<span style="color: green;">&#41;</span> `pairR` <span style="color: green;">&#40;</span>d `Stepper` de<span style="color: green;">&#41;</span> =
  <span style="color: green;">&#40;</span>c,d<span style="color: green;">&#41;</span> `stepper` pairE <span style="color: green;">&#40;</span>c,d<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>ce,de<span style="color: green;">&#41;</span></pre>
</div></p>

<p>or, more directly:</p>

<p><div>
<pre class="haskell"><span style="color: green;">&#40;</span>c `Stepper` ce<span style="color: green;">&#41;</span> `pairR` <span style="color: green;">&#40;</span>d `Stepper` de<span style="color: green;">&#41;</span> =
  <span style="color: green;">&#40;</span>c,d<span style="color: green;">&#41;</span> `accumR` pairEditE <span style="color: green;">&#40;</span>ce,de<span style="color: green;">&#41;</span></pre>
</div></p>

<p>Lovely!</p>

<h3>Pair editing and applicative functors</h3>

<p>In a sense, we&#8217;ve gone to a lot of work for nothing.  Since <code>Reactive</code> is an applicative functor, we can also give this trivially easy and much more general definition:</p>

<p><div>
<pre class="haskell">pairR :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#t:Applicative"><span style="color: #833; font-weight: bold;">Applicative</span></a> f =&gt; f c -&gt; f d -&gt; f <span style="color: green;">&#40;</span>c,d<span style="color: green;">&#41;</span>
pairR = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:liftA2"><span style="font-weight: bold;">liftA2</span></a> <span style="color: green;">&#40;</span>,<span style="color: green;">&#41;</span></pre>
</div></p>

<p>On the other hand, the <code>(&lt;*&gt;)</code> method in the <code>Applicative</code> instance given in <a href="http://conal.net/blog/posts/reactive-normal-form/" title="Blog post: &quot;Reactive normal form&quot;">Reactive normal form</a> was tricky.  We can now replace it with a simple definition in terms of <code>pairR</code> (assuming we don&#8217;t define <code>pairR</code> in terms of <code>liftA2</code>).  Use <code>pairR</code> to turn a reactive function and a reactive argument into a reactive function/argument pair.  Then map uncurried function application to get <code>(&lt;*&gt;)</code>:</p>

<p><div>
<pre class="haskell">rf &lt;*&gt; rx = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:uncurry"><span style="font-weight: bold;">uncurry</span></a> <span style="color: green;">&#40;</span>$<span style="color: green;">&#41;</span> &lt;$&gt; <span style="color: green;">&#40;</span>rf `pairR` rx<span style="color: green;">&#41;</span></pre>
</div></p>

<p>I like how these new definitions of <code>pairR</code> and <code>(&lt;*&gt;)</code> build on other generally useful combinators.  In contrast, my previous <code>(&lt;*&gt;)</code> definition is recursive and uses the representation of reactive values and events.</p>
]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/pairs-sums-and-reactivity/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Applicative bots</title>
		<link>http://conal.net/blog/posts/applicative-bots/</link>
		<comments>http://conal.net/blog/posts/applicative-bots/#comments</comments>
		<pubDate>Wed, 13 Feb 2008 06:30:43 +0000</pubDate>
		<dc:creator>conal</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[applicative functor]]></category>
		<category><![CDATA[bot]]></category>
		<category><![CDATA[correction]]></category>
		<category><![CDATA[FRP]]></category>
		<category><![CDATA[functional reactive programming]]></category>
		<category><![CDATA[lead/follow]]></category>

		<guid isPermaLink="false">http://conal.net/blog/posts/applicative-bots/</guid>
		<description><![CDATA[]]></description>
			<content:encoded><![CDATA[<!-- 

Title: Applicative bots

Tags: functional reactive programming, FRP, applicative functors, bot, lead/follow, correction

-->

<!-- references -->

<!-- teaser -->

<p>In <a href="http://conal.net/blog/posts/functional-reactive-partner-dancing/" title="Blog post: &quot;Functional reactive partner dancing&quot;">Functional reactive partner dancing</a>, I mentioned that (a) the partially applied leading and following types have boilerplate <code>Applicative</code> instances, and (b) the leading type corresponds to <a href="http://conal.net/blog/posts/reactive-values-from-the-future/" title="Blog post: &quot;Reactive values from the future&quot;">varying (reactive) values</a>.  Today I realized that those boilerplate instances are not very useful, and that they <em>do not</em> correspond to the <code>Applicative</code> instance of <code>Reactive</code>.  In this post, I give a useful <code>Applicative</code> instance that does correspond to the <code>Reactive</code> instance.  The instance definition is expressed in terms of the pair editor bot shown at the end of the &#8220;dancing&#8221; post, which seems to have a variety of applications.</p>

<p>The <code>Applicative</code> instance has one awkward aspect that suggests a tweak to the formulation of leading.  I give simplified versions of pair editing and <code>Applicative</code> for the revised type. This change is in <a href="http://hackage.haskell.org/cgi-bin/hackage-scripts/package/bot-0.1" title="Haskell package: bot">version 0.1</a> of the <a href="http://haskell.org/haskellwiki/Bot" title="Wiki page for the Bot library">Bot</a> libary.</p>

<p><em>Edit 2008-02-15</em>: added FRP tags; prose tweak.</p>

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

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

<h3>Oops</h3>

<p>The multi-output versions of leading and following are formulated simply as the single-output versions, with a list-valued output type:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">newtype</span> a :-&gt; b = Follows <span style="color: green;">&#40;</span>Follow a <span style="color: green;">&#91;</span>b<span style="color: green;">&#93;</span><span style="color: green;">&#41;</span>
<span style="color: #050; font-weight: bold;">newtype</span> a :&gt;- b = Leads   <span style="color: green;">&#40;</span>Lead   a <span style="color: green;">&#91;</span>b<span style="color: green;">&#93;</span><span style="color: green;">&#41;</span></pre>
</div></p>

<p>Partially applied, each of these types is a sort of composition of type constructors.  For instance, <code>(:-&gt;) a</code> is the type composition of <code>Follow a</code> and <code>[]</code>.  Since both of those type constructors are applicative functors, there are standard definitions of <code>Functor</code> and <code>Applicative</code>.</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="color: #833; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>:-&gt;<span style="color: green;">&#41;</span> i<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>Follows z<span style="color: green;">&#41;</span> = Follows <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a>.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a><span style="color: green;">&#41;</span> f z<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#t:Applicative"><span style="color: #833; font-weight: bold;">Applicative</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>:-&gt;<span style="color: green;">&#41;</span> i<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a> x                  = Follows <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a>.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a><span style="color: green;">&#41;</span> x<span style="color: green;">&#41;</span>
  Follows f &lt;*&gt; Follows x = Follows <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:liftA2"><span style="font-weight: bold;">liftA2</span></a> <span style="color: green;">&#40;</span>&lt;*&gt;<span style="color: green;">&#41;</span> f x<span style="color: green;">&#41;</span></pre>
</div></p>

<p>and similarly for <code>(:&gt;-) i</code>.</p>

<p>In fact, these instance templates are abstracted into instances for the type composition operator <code>(:.)</code> found in <a href="http://haskell.org/haskellwiki/TypeCompose" title="Wiki page for the TypeCompose library">TypeCompose</a>, so we can get the four instances for free if we define</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">type</span> <span style="color: green;">&#40;</span>:-&gt;<span style="color: green;">&#41;</span> a = Follow a :. <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span>
<span style="color: #050; font-weight: bold;">type</span> <span style="color: green;">&#40;</span>:&gt;-<span style="color: green;">&#41;</span> a = Lead   a :. <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span></pre>
</div></p>

<p>While the <code>Functor</code> instances work fine, the rub (which I didn&#8217;t realize when writing the &#8220;dancing&#8221; post) is that the <code>Applicative</code> instances are not what I want.  They delegate to the <code>Applicative</code> instances for <code>Follow a</code> and for <code>[]</code>.  The result is that each output of <code>lf &lt;*&gt; lx</code> is the list of <code>f x</code> for all <code>f</code> in the (list-valued) <code>lf</code> output at that point and all <code>x</code> in the (list-valued) <code>lx</code> output.  In particular, the <code>lf &lt;*&gt; lx</code> will have an output only when <em>both</em> <code>lf</code> and <code>lx</code> have simultaneous outputs.</p>

<p>Instead, I&#8217;d like <code>lf &lt;*&gt; lx</code> to have an output whenever <em>either</em> <code>lf</code> or <code>lx</code> has an output.  If <code>lf</code> has an output <code>f</code>, I want to output <code>f x</code>, where <code>x</code> is the most recent <code>lx</code> output.  Similarly, if <code>lx</code> has an output, I want to output <code>f x</code>, where <code>f</code> is the most recent <code>lf</code> output.  This behavior is exactly how <code>Applicative</code> works for <code>Reactive</code>, as described in <a href="http://conal.net/blog/posts/reactive-normal-form/" title="Blog post: &quot;Reactive normal form&quot;">reactive-normal-form</a>.</p>

<h3>A solution and a problem</h3>

<p>At the end of <a href="http://conal.net/blog/posts/functional-reactive-partner-dancing/" title="Blog post: &quot;Functional reactive partner dancing&quot;">Functional reactive partner dancing</a>, I showed a tool that is related to the desired <code>Applicative</code> behavior.</p>

<p><div>
<pre class="haskell">editPairF :: <span style="color: green;">&#40;</span>c,d<span style="color: green;">&#41;</span> -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="color: #833; font-weight: bold;">Either</span></a> c d :-&gt; <span style="color: green;">&#40;</span>c,d<span style="color: green;">&#41;</span></pre>
</div></p>

<p>Given an initial pair, <code>editPairF</code> accepts replacements of either the first or second element and produces updated pairs, remembering the previous values.  Since memory is involved, <code>editPairL</code> is defined in terms of the generic accumulation combinator <code>accumF</code>.</p>

<p>Let&#8217;s put <code>editPairF</code> to work, to pair up two follows into a pair-valued follow.  A new pair is output whenever either element gets output.</p>

<p><div>
<pre class="haskell">pairF :: <span style="color: green;">&#40;</span>b,c<span style="color: green;">&#41;</span> -&gt; a:-&gt;b -&gt; a:-&gt;c -&gt; a:-&gt;<span style="color: green;">&#40;</span>b,c<span style="color: green;">&#41;</span>
pairF bc ab ac = <span style="color: green;">&#40;</span>Left &lt;$&gt; ab<span style="color: green;">&#41;</span> `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` <span style="color: green;">&#40;</span>Right &lt;$&gt; ac<span style="color: green;">&#41;</span> &gt;&gt;&gt; editPairF bc</pre>
</div></p>

<p>We had to supply the initial pair here, because follows don&#8217;t have initial values.  Leads do, however, so the lead-pairing function has a simpler-looking type:</p>

<p><div>
<pre class="haskell">pairL :: a:&gt;-b -&gt; a:&gt;-c -&gt; a:&gt;-<span style="color: green;">&#40;</span>b,c<span style="color: green;">&#41;</span></pre>
</div></p>

<p>The definition of <code>pairL</code> works in terms of <code>pairF</code>.  The extra work involves disassembling and reassembling leads into and from initial values and follows.</p>

<p><div>
<pre class="haskell">ab `pairL` ac =
  leads <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:liftA2"><span style="font-weight: bold;">liftA2</span></a> <span style="color: green;">&#40;</span>,<span style="color: green;">&#41;</span> bs cs<span style="color: green;">&#41;</span> $ pairF <span style="color: green;">&#40;</span>b,c<span style="color: green;">&#41;</span> abf acf
 <span style="color: #050; font-weight: bold;">where</span>
   <span style="color: green;">&#40;</span>bs,abf<span style="color: green;">&#41;</span> = splitL ab
   <span style="color: green;">&#40;</span>cs,acf<span style="color: green;">&#41;</span> = splitL ac
   <span style="color: #5d478b; font-style: italic;">-- Oh dear.  b &amp; c might not be well-defined</span>
   b = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:last"><span style="font-weight: bold;">last</span></a> bs
   c = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:last"><span style="font-weight: bold;">last</span></a> cs</pre>
</div></p>

<p>The awkward bit here is that, as formulated, a multi-lead (<code>a :&gt;- b</code>) could have multiple values even initially.  For that reason, I (a) use a cross product (<code>liftA2 (,)</code>) for the initial pairs, and (b) extract a single value from each lead to use in the pair-valued lead&#8217;s initial value.  This second consideration is worse than awkward; it will fail if either initial value list is empty.</p>

<p>Is it really useful for a lead to have an initial <em>list</em> of values?  Not that I know of.  I allowed the flexibility because it made the type definitions so simple and uniform, which I&#8217;ve found has a decisive impact on the simplicity of code that works on the type.</p>

<p>Placing the initial-list problem aside for now, here is the simple and useful Applicative instance for leads.  The <code>pure</code> method makes a lead with an initial value an no future reponses.  The <code>(&lt;*&gt;)</code> method uses <code>pairL</code> above to make a lead whose outputs are function/argument pairs, and then maps uncurried function application onto the pairs to get out the results.</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#t:Applicative"><span style="color: #833; font-weight: bold;">Applicative</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>:&gt;-<span style="color: green;">&#41;</span> i<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a> x    = leads <span style="color: green;">&#91;</span>x<span style="color: green;">&#93;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a>
  lf &lt;*&gt; lx = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:uncurry"><span style="font-weight: bold;">uncurry</span></a> <span style="color: green;">&#40;</span>$<span style="color: green;">&#41;</span> &lt;$&gt; <span style="color: green;">&#40;</span>lf `pairL` lx<span style="color: green;">&#41;</span></pre>
</div></p>

<p>What about <code>(:-&gt;)</code> (following)?  I don&#8217;t think an <code>Applicative</code> instance like the leading one can exist, due to lack of initial values.  Perhaps there is an <code>Applicative</code> instance corresponding to the <a href="http://conal.net/blog/posts/reactive-values-from-the-future/" title="Blog post: &quot;Reactive values from the future&quot;">one on Event</a> (combining all pairs of occurrences over time).</p>

<h3>A tweak, and we&#8217;re back to safe &amp; elegant</h3>

<p>The difficulty with <code>pairL</code> comes from a feature of dubious value, namely having an initial list of values rather than exactly one initial value.  Let&#8217;s consider removing that flexibility.  Replace</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">newtype</span> a :&gt;- b = Leads <span style="color: green;">&#40;</span>Lead a <span style="color: green;">&#91;</span>b<span style="color: green;">&#93;</span><span style="color: green;">&#41;</span></pre>
</div></p>

<p>with</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">newtype</span> a :&gt;- b = Leads <span style="color: green;">&#40;</span>b, a :-&gt; b<span style="color: green;">&#41;</span></pre>
</div></p>

<p>The pairing combinator for leads is now simpler.  It&#8217;s also bomb-proof, since it has initial single values instead of lists:</p>

<p><div>
<pre class="haskell">pairL :: a:&gt;-b -&gt; a:&gt;-c -&gt; a:&gt;-<span style="color: green;">&#40;</span>b,c<span style="color: green;">&#41;</span>
Leads <span style="color: green;">&#40;</span>a,fa<span style="color: green;">&#41;</span> `pairL` Leads <span style="color: green;">&#40;</span>b,fb<span style="color: green;">&#41;</span> =
  Leads <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span>, pairF <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> fa fb<span style="color: green;">&#41;</span></pre>
</div></p>

<p>And we have simple and (I think) trouble-free instances:</p>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="color: #833; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>:&gt;-<span style="color: green;">&#41;</span> i<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>Leads <span style="color: green;">&#40;</span>b,fol<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> = Leads <span style="color: green;">&#40;</span>f b, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f fol<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#t:Applicative"><span style="color: #833; font-weight: bold;">Applicative</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>:&gt;-<span style="color: green;">&#41;</span> i<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a> x    = Leads <span style="color: green;">&#40;</span>x,<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mempty"><span style="font-weight: bold;">mempty</span></a><span style="color: green;">&#41;</span>
  lf &lt;*&gt; lx = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:uncurry"><span style="font-weight: bold;">uncurry</span></a> <span style="color: green;">&#40;</span>$<span style="color: green;">&#41;</span> &lt;$&gt; <span style="color: green;">&#40;</span>lf `pairL` lx<span style="color: green;">&#41;</span></pre>
</div></p>
]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/applicative-bots/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</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>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[]]></description>
			<content:encoded><![CDATA[<!-- 

Title: Functional reactive partner dancing

Tags: functional reactive programming, FRP, bot, mutant, dance, lead/follow, arrows, functors, applicative functors

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>

<p><div>
<pre class="haskell">a -&gt; <span style="color: green;">&#40;</span>b, a -&gt; <span style="color: green;">&#40;</span>b, a -&gt; <span style="color: green;">&#40;</span>b, ...<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre>
</div></p>

<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>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">newtype</span> a `MutantBot` b = Mutant <span style="color: green;">&#40;</span>a -&gt; <span style="color: green;">&#40;</span>b, a `MutantBot` b<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre>
</div></p>

<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>

<p><div>
<pre class="haskell">a -&gt; <span style="color: green;">&#40;</span>b, a -&gt; <span style="color: green;">&#40;</span>b, a -&gt; <span style="color: green;">&#40;</span>b, ...<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre>
</div></p>

<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>

<p><div>
<pre class="haskell"><span style="color: green;">&#40;</span>a, b -&gt; <span style="color: green;">&#40;</span>a, b -&gt; <span style="color: green;">&#40;</span>a, b -&gt; ...<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre>
</div></p>

<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>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">type</span> a `Follow` b =  a -&gt; Lead a b
<span style="color: #050; font-weight: bold;">type</span> a `Lead`   b = <span style="color: green;">&#40;</span>b, Follow a b<span style="color: green;">&#41;</span></pre>
</div></p>

<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>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">newtype</span> a `Follow` b = Follow <span style="color: green;">&#40;</span>a -&gt; Lead a b<span style="color: green;">&#41;</span>
<span style="color: #050; font-weight: bold;">newtype</span> a `Lead`   b =   Lead <span style="color: green;">&#40;</span>b, Follow a b<span style="color: green;">&#41;</span></pre>
</div></p>

<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>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="color: #833; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>Follow a<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>Follow h<span style="color: green;">&#41;</span> = Follow <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f . h<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#t:Applicative"><span style="color: #833; font-weight: bold;">Applicative</span></a> <span style="color: green;">&#40;</span>Follow a<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a> b = Follow <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a> b<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
  Follow h &lt;*&gt; Follow k = Follow $ \ a -&gt; h a &lt;*&gt; k a
&nbsp;
<span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="color: #833; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>Lead a<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>Lead <span style="color: green;">&#40;</span>b, g<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> = Lead <span style="color: green;">&#40;</span>f b, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f g<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #050; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#t:Applicative"><span style="color: #833; font-weight: bold;">Applicative</span></a> <span style="color: green;">&#40;</span>Lead a<span style="color: green;">&#41;</span> <span style="color: #050; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a> b = Lead <span style="color: green;">&#40;</span>b, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a> b<span style="color: green;">&#41;</span>
  Lead <span style="color: green;">&#40;</span>f,pf<span style="color: green;">&#41;</span> &lt;*&gt; Lead <span style="color: green;">&#40;</span>a,pa<span style="color: green;">&#41;</span> = Lead <span style="color: green;">&#40;</span>f a, pf &lt;*&gt; pa<span style="color: green;">&#41;</span></pre>
</div></p>

<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>

<p><div>
<pre class="haskell"><span style="color: #5d478b; font-style: italic;">-- | Precomposition with a pure function.</span>
<span style="color: green;">&#40;</span>^&gt;&gt;<span style="color: green;">&#41;</span> :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Arrow.html#t:Arrow"><span style="color: #833; font-weight: bold;">Arrow</span></a> <span style="color: green;">&#40;</span>~&gt;<span style="color: green;">&#41;</span> =&gt; <span style="color: green;">&#40;</span>b -&gt; c<span style="color: green;">&#41;</span> -&gt; c ~&gt; d -&gt; b ~&gt; d
f ^&gt;&gt; a = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Arrow.html#v:arr"><span style="font-weight: bold;">arr</span></a> f &gt;&gt;&gt; a</pre>
</div></p>

<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>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">newtype</span> Event b = Future <span style="color: green;">&#40;</span>Reactive b<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #050; font-weight: bold;">data</span> Reactive b = Stepper b <span style="color: green;">&#40;</span>Event b<span style="color: green;">&#41;</span></pre>
</div></p>

<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>

<p><div>
<pre class="haskell"><span style="color: #050; font-weight: bold;">newtype</span> a :&gt;- b = Leads   <span style="color: green;">&#40;</span>Lead   a <span style="color: green;">&#91;</span>b<span style="color: green;">&#93;</span><span style="color: green;">&#41;</span>
<span style="color: #050; font-weight: bold;">newtype</span> a :-&gt; b = Follows <span style="color: green;">&#40;</span>Follow a <span style="color: green;">&#91;</span>b<span style="color: green;">&#93;</span><span style="color: green;">&#41;</span></pre>
</div></p>

<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>

<p><div>
<pre class="haskell">Reactive <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #833; font-weight: bold;">Int</span></a> -&gt; Reactive <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #833; font-weight: bold;">Int</span></a> -&gt; Reactive <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #833; font-weight: bold;">Int</span></a></pre>
</div></p>

<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>

<p><div>
<pre class="haskell"><span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #833; font-weight: bold;">Int</span></a>,<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #833; font-weight: bold;">Int</span></a><span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>Event <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #833; font-weight: bold;">Int</span></a>, Event <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #833; font-weight: bold;">Int</span></a><span style="color: green;">&#41;</span> -&gt; Reactive <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #833; font-weight: bold;">Int</span></a></pre>
</div></p>

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

<p><div>
<pre class="haskell"><span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #833; font-weight: bold;">Int</span></a>,<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #833; font-weight: bold;">Int</span></a><span style="color: green;">&#41;</span> -&gt; Event <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="color: #833; font-weight: bold;">Either</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #833; font-weight: bold;">Int</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #833; font-weight: bold;">Int</span></a><span style="color: green;">&#41;</span> -&gt; Reactive <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #833; font-weight: bold;">Int</span></a></pre>
</div></p>

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

<p><div>
<pre class="haskell">prod :: <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #833; font-weight: bold;">Int</span></a>,<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #833; font-weight: bold;">Int</span></a><span style="color: green;">&#41;</span> -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="color: #833; font-weight: bold;">Either</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #833; font-weight: bold;">Int</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #833; font-weight: bold;">Int</span></a> :&gt;- <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #833; font-weight: bold;">Int</span></a></pre>
</div></p>

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

<p><div>
<pre class="haskell">updPair :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="color: #833; font-weight: bold;">Either</span></a> c d -&gt; <span style="color: green;">&#40;</span>c,d<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>c,d<span style="color: green;">&#41;</span>
updPair <span style="color: green;">&#40;</span>Left  c'<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>_,d<span style="color: green;">&#41;</span> = <span style="color: green;">&#40;</span>c',d<span style="color: green;">&#41;</span>
updPair <span style="color: green;">&#40;</span>Right d'<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>c,_<span style="color: green;">&#41;</span> = <span style="color: green;">&#40;</span>c,d'<span style="color: green;">&#41;</span></pre>
</div></p>

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

<p><div>
<pre class="haskell">updPair = <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Arrow.html#v:first"><span style="font-weight: bold;">first</span></a>.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a><span style="color: green;">&#41;</span> `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:either"><span style="font-weight: bold;">either</span></a>` <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Arrow.html#v:second"><span style="font-weight: bold;">second</span></a>.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a><span style="color: green;">&#41;</span></pre>
</div></p>

<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>

<p><div>
<pre class="haskell">editPairF :: <span style="color: green;">&#40;</span>c,d<span style="color: green;">&#41;</span> -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="color: #833; font-weight: bold;">Either</span></a> c d :-&gt; <span style="color: green;">&#40;</span>c,d<span style="color: green;">&#41;</span>
editPairF cd = updPair ^&gt;&gt; accumF cd</pre>
</div></p>

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

<p><div>
<pre class="haskell">editPairL :: <span style="color: green;">&#40;</span>c,d<span style="color: green;">&#41;</span> -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="color: #833; font-weight: bold;">Either</span></a> c d :&gt;- <span style="color: green;">&#40;</span>c,d<span style="color: green;">&#41;</span>
editPairL cd = leads <span style="color: green;">&#91;</span>cd<span style="color: green;">&#93;</span> <span style="color: green;">&#40;</span>editPairF cd<span style="color: green;">&#41;</span></pre>
</div></p>

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

<p><div>
<pre class="haskell">    editPairL = leads.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a> &lt;*&gt; editPairF</pre>
</div></p>

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

<p><div>
<pre class="haskell">leads :: <span style="color: green;">&#91;</span>b<span style="color: green;">&#93;</span> -&gt; a :-&gt; b -&gt; a :&gt;- b
leads bs <span style="color: green;">&#40;</span>Follows fol<span style="color: green;">&#41;</span> = Leads <span style="color: green;">&#40;</span>Lead <span style="color: green;">&#40;</span>bs,fol<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre>
</div></p>

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

<p><div>
<pre class="haskell">prod = <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a>.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a><span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:uncurry"><span style="font-weight: bold;">uncurry</span></a> <span style="color: green;">&#40;</span>*<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> editPairL</pre>
</div></p>

<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>
]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/functional-reactive-partner-dancing/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<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>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[]]></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>

<p><div>
<pre class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:scanl"><span style="font-weight: bold;">scanl</span></a> :: <span style="color: green;">&#40;</span>b -&gt; a -&gt; b<span style="color: green;">&#41;</span> -&gt; b -&gt; <span style="color: green;">&#91;</span>a<span style="color: green;">&#93;</span> -&gt; <span style="color: green;">&#91;</span>b<span style="color: green;">&#93;</span>
&nbsp;
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:scanl"><span style="font-weight: bold;">scanl</span></a> op b0 <span style="color: green;">&#91;</span>a1, a2, ...<span style="color: green;">&#93;</span> == <span style="color: green;">&#91;</span>b0, b0 `op` a1, <span style="color: green;">&#40;</span>b0 `op` a1<span style="color: green;">&#41;</span> `op` a2, ...<span style="color: green;">&#93;</span></pre>
</div></p>

<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>

<p><div>
<pre class="haskell">scanlTl :: <span style="color: green;">&#40;</span>b -&gt; a -&gt; b<span style="color: green;">&#41;</span> -&gt; b -&gt; <span style="color: green;">&#91;</span>a<span style="color: green;">&#93;</span> -&gt; <span style="color: green;">&#91;</span>b<span style="color: green;">&#93;</span>
scanlTl _ _ <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span>     = <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span>
scanlTl f b <span style="color: green;">&#40;</span>a:<span style="color: #050; font-weight: bold;">as</span><span style="color: green;">&#41;</span> = <span style="color: #050; font-weight: bold;">let</span> b' = f b a <span style="color: #050; font-weight: bold;">in</span> b' : scanlTl f b' <span style="color: #050; font-weight: bold;">as</span></pre>
</div></p>

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

<p><div>
<pre class="haskell">accum :: a -&gt; <span style="color: green;">&#91;</span>a-&gt;a<span style="color: green;">&#93;</span> -&gt; <span style="color: green;">&#91;</span>a<span style="color: green;">&#93;</span>
accum _ <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span> = <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span>
accum a <span style="color: green;">&#40;</span>f:fs<span style="color: green;">&#41;</span> = a' : accum a' fs <span style="color: #050; font-weight: bold;">where</span> a' = f a</pre>
</div></p>

<p>or just</p>

<p><div>
<pre class="haskell">accum = scanlTl <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:flip"><span style="font-weight: bold;">flip</span></a> <span style="color: green;">&#40;</span>$<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre>
</div></p>

<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>

<p><div>
<pre class="haskell">scanlM :: <span style="color: green;">&#40;</span>b -&gt; a -&gt; b<span style="color: green;">&#41;</span> -&gt; b -&gt; MutantBot a b
scanlM f b = Automaton $ \ a -&gt; <span style="color: #050; font-weight: bold;">let</span> b' = f b a <span style="color: #050; font-weight: bold;">in</span> <span style="color: green;">&#40;</span>b', scanlM f b'<span style="color: green;">&#41;</span></pre>
</div></p>

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

<p><div>
<pre class="haskell">accumM :: a -&gt; MutantBot <span style="color: green;">&#40;</span>a-&gt;a<span style="color: green;">&#41;</span> a
accumM = scanlM <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:flip"><span style="font-weight: bold;">flip</span></a> <span style="color: green;">&#40;</span>$<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre>
</div></p>

<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>

<p><div>
<pre class="haskell">scanlC :: <span style="color: green;">&#40;</span>b -&gt; a -&gt; b<span style="color: green;">&#41;</span> -&gt; b -&gt; <span style="color: green;">&#40;</span>a :~&gt; b<span style="color: green;">&#41;</span>
scanlC f b = Chatter $ <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#v:pure"><span style="font-weight: bold;">pure</span></a> &lt;$&gt; scanlM f b
&nbsp;
accumC :: a -&gt; <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>a-&gt;a<span style="color: green;">&#41;</span> :~&gt; a<span style="color: green;">&#41;</span>
accumC = scanlC <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:flip"><span style="font-weight: bold;">flip</span></a> <span style="color: green;">&#40;</span>$<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre>
</div></p>

<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>

<p><div>
<pre class="haskell">count :: a :-&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #833; font-weight: bold;">Int</span></a>
count = scanlC <span style="color: green;">&#40;</span>\ b _ -&gt; b + <span style="color: red;">1</span><span style="color: green;">&#41;</span> <span style="color: red;">0</span></pre>
</div></p>

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

<p><div>
<pre class="haskell">flipFlop :: a :-&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="color: #833; font-weight: bold;">Bool</span></a>
flipFlop = scanlC <span style="color: green;">&#40;</span>\ b _ -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:not"><span style="font-weight: bold;">not</span></a> b<span style="color: green;">&#41;</span> False</pre>
</div></p>

<p>Add up inputs:</p>

<p><div>
<pre class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:sum"><span style="font-weight: bold;">sum</span></a> :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="color: #833; font-weight: bold;">Num</span></a> a =&gt; a :-&gt; a
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:sum"><span style="font-weight: bold;">sum</span></a> = scanlC <span style="color: green;">&#40;</span>+<span style="color: green;">&#41;</span> <span style="color: red;">0</span></pre>
</div></p>

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

<p><div>
<pre class="haskell">coundOdd :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Integral"><span style="color: #833; font-weight: bold;">Integral</span></a> a =&gt; a :-&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #833; font-weight: bold;">Int</span></a>
coundOdd = filterC <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:odd"><span style="font-weight: bold;">odd</span></a> &gt;&gt;&gt; count</pre>
</div></p>

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

<p><div>
<pre class="haskell">upDown :: <span style="color: #050; font-weight: bold;">forall</span> a. <span style="color: green;">&#40;</span>a -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="color: #833; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>a -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="color: #833; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> -&gt; a :-&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #833; font-weight: bold;">Int</span></a>
upDown isUp isDown = <span style="color: green;">&#40;</span>up `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html#v:mappend"><span style="font-weight: bold;">mappend</span></a>` down<span style="color: green;">&#41;</span> &gt;&gt;&gt; accumC <span style="color: red;">0</span>
 <span style="color: #050; font-weight: bold;">where</span>
   up, down :: a :-&gt; <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #833; font-weight: bold;">Int</span></a> -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #833; font-weight: bold;">Int</span></a><span style="color: green;">&#41;</span>
   up   = filterC isUp   &gt;&gt;&gt; replace <span style="color: green;">&#40;</span>+ <span style="color: red;">1</span><span style="color: green;">&#41;</span>
   down = filterC isDown &gt;&gt;&gt; replace <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:subtract"><span style="font-weight: bold;">subtract</span></a> <span style="color: red;">1</span><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- Respond to each input with the same value</span>
replace :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Arrow.html#t:Arrow"><span style="color: #833; font-weight: bold;">Arrow</span></a> <span style="color: green;">&#40;</span>~&gt;<span style="color: green;">&#41;</span> =&gt; b -&gt; a ~&gt; b
replace b = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Arrow.html#v:arr"><span style="font-weight: bold;">arr</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a> b<span style="color: green;">&#41;</span></pre>
</div></p>

<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>
]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/accumulation-for-functional-reactive-chatter-bots/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
