<?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; monoid</title>
	<atom:link href="http://conal.net/blog/tag/monoid/feed" rel="self" type="application/rss+xml" />
	<link>http://conal.net/blog</link>
	<description>Inspirations &#38; experiments, mainly about denotative/functional programming in Haskell</description>
	<lastBuildDate>Thu, 25 Jul 2019 18:15:11 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=4.1.17</generator>
	<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=conal&amp;popout=1&amp;url=http%3A%2F%2Fconal.net%2Fblog%2F&amp;language=en_US&amp;category=text&amp;title=Conal+Elliott&amp;description=Inspirations+%26amp%3B+experiments%2C+mainly+about+denotative%2Ffunctional+programming+in+Haskell&amp;tags=blog" type="text/html" />
	<item>
		<title>Denotational design with type class morphisms</title>
		<link>http://conal.net/blog/posts/denotational-design-with-type-class-morphisms</link>
		<comments>http://conal.net/blog/posts/denotational-design-with-type-class-morphisms#comments</comments>
		<pubDate>Thu, 19 Feb 2009 02:34:08 +0000</pubDate>
		<dc:creator><![CDATA[Conal]]></dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[applicative functor]]></category>
		<category><![CDATA[arrow]]></category>
		<category><![CDATA[associated type]]></category>
		<category><![CDATA[functor]]></category>
		<category><![CDATA[monad]]></category>
		<category><![CDATA[monoid]]></category>
		<category><![CDATA[paper]]></category>
		<category><![CDATA[semantics]]></category>
		<category><![CDATA[trie]]></category>
		<category><![CDATA[type class morphism]]></category>

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

Title: Denotational design with type class morphisms

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

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

-->

<!-- references -->

<!-- teaser -->

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

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

<p>The abstract:</p>

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

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

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

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

<!--
**Edits**:

* 2009-02-09: just fiddling around
-->
<p><a href="http://conal.net/blog/?flattrss_redirect&amp;id=84&amp;md5=8ce3b83d01ccfad97ade1469b72d2a04"><img src="http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png" srcset="http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png, http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white@2x.png 2xhttp://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png, http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white@3x.png 3x" alt="Flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/denotational-design-with-type-class-morphisms/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=conal&amp;popout=1&amp;url=http%3A%2F%2Fconal.net%2Fblog%2Fposts%2Fdenotational-design-with-type-class-morphisms&amp;language=en_GB&amp;category=text&amp;title=Denotational+design+with+type+class+morphisms&amp;description=I%26%238217%3Bve+just+finished+a+draft+of+a+paper+called+Denotational+design+with+type+class+morphisms%2C+for+submission+to+ICFP+2009.+The+paper+is+on+a+theme+I%26%238217%3Bve+explored+in+several...&amp;tags=applicative+functor%2Carrow%2Cassociated+type%2Cfunctor%2Cmonad%2Cmonoid%2Cpaper%2Csemantics%2Ctrie%2Ctype+class+morphism%2Cblog" type="text/html" />
	</item>
		<item>
		<title>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><![CDATA[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[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 Reactive. A closer look revealed a closer connection still, as described in this post. [&#8230;]]]></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>

<pre><code>type Rendering = Image Color

render :: Geometry -&gt; Rendering
</code></pre>

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

<pre><code>union :: Geometry -&gt; Geometry -&gt; Geometry
</code></pre>

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

<pre><code>forall ga gb. render (ga `union` gb) == render ga `unionR` render gb
</code></pre>

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

<pre><code>type RenderingD = Image (Depth, Color)  -- first try

renderD :: Geometry -&gt; RenderingD
</code></pre>

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

<pre><code>forall ga gb. renderD (ga `union` gb) == renderD ga `unionR` renderD gb
</code></pre>

<p>where</p>

<pre><code>unionR :: RenderingD -&gt; RenderingD -&gt; RenderingD

unionR im im' p = if d &lt;= d' then (d,c) else (d',c')
 where
   (d ,c ) = im  p
   (d',c') = im' p
</code></pre>

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

<pre><code>render g = snd . renderD g
</code></pre>

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

<pre><code>render = (result.result) snd renderD
</code></pre>

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

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

<p>So that</p>

<pre><code>unionR = liftA2 closer

closer (d,c) (d',c') = if d &lt;= d' then (d,c) else (d',c')
</code></pre>

<p>Or</p>

<pre><code>closer dc@(d,_) dc'@(d',_) = if d &lt;= d' then dc else dc'
</code></pre>

<p>Or even</p>

<pre><code>closer = minBy fst
</code></pre>

<p>where</p>

<pre><code>minBy f u v = if f u &lt;= f v then u else v
</code></pre>

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

<pre><code>unionR :: (Ord a, Applicative f) =&gt; f (a,b) -&gt; f (a,b) -&gt; f (a,b)

closer :: Ord a =&gt; (a,b) -&gt; (a,b) -&gt; (a,b)
</code></pre>

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

<pre><code>forall ga gb. renderD (ga `op` gb) == renderD ga `op` renderD gb
</code></pre>

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

<pre><code>instance Monoid Geometry where
  mempty  = emptyGeometry
  mappend = union
</code></pre>

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

<pre><code>instance Monoid b =&gt; Monoid (a -&gt; b) where
  mempty = const mempty
  f `mappend` g =  a -&gt; f a `mappend` g a
</code></pre>

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

<pre><code>instance Applicative ((-&gt;) a) where
  pure      = const
  hf &lt;*&gt; xf =  a -&gt; (hf a) (xf a)

instance Monoid b =&gt; Monoid (a -&gt; b) where
  mempty  = pure   mempty
  mappend = liftA2 mappend
</code></pre>

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

<pre><code>instance (Monoid a, Monoid b) =&gt; Monoid (a,b) where
  mempty = (mempty,mempty)
  (a,b) `mappend` (a',b') = (a `mappend` a', b `mappend` b')
</code></pre>

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

<pre><code>data DepthG d a = Depth d a  -- first try
</code></pre>

<p>Alternatively,</p>

<pre><code>newtype DepthG d a = Depth { unDepth :: (d,a) }
</code></pre>

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

<pre><code>instance Monoid (DepthG d a) where
  mempty  = Depth (maxBound,undefined)
  Depth p `mappend` Depth p' = Depth (p `closer` p')
</code></pre>

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

<pre><code>  mappend = inDepth2 closer
</code></pre>

<p>where</p>

<pre><code>  inDepth2 = unDepth ~&gt; unDepth ~&gt; Depth
</code></pre>

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

<pre><code>newtype FutureG t a = Future (Time t, a)

instance (Ord t, Bounded t) =&gt; Monoid (FutureG t a) where
  mempty = Future (maxBound, undefined)
  Future (s,a) `mappend` Future (t,b) =
    Future (s `min` t, if s &lt;= t then a else b)
</code></pre>

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

<pre><code>  mappend = minBy futTime

  futTime (Future (t,_)) = t
</code></pre>

<p>Equivalently,</p>

<pre><code>  mappend = inFuture2 (minBy fst)
</code></pre>

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

<pre><code>type RenderingD d = Image (FutureG d Color)
renderD :: (Ord d, Bounded d) =&gt; Geometry -&gt; RenderingD d
</code></pre>

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

<pre><code>renderD mempty == mempty

renderD (ga `mappend` gb) == renderD ga `mappend` renderD gb
</code></pre>

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

<pre><code>newtype PastG t a = Past (FutureG t a)
  deriving (Monoid, Functor, Applicative, Monad)
</code></pre>

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

<pre><code>type RenderingD d = Image [FutureG d Color]  -- multiple projections, first try
</code></pre>

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

<pre><code>type RenderingD d = Image (EventG d Color)

renderD :: (Ord d, Bounded d) =&gt; Geometry -&gt; RenderingD d
</code></pre>

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

<pre><code>(*%)  :: Transform3 -&gt; Geometry -&gt; Geometry
</code></pre>

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

<pre><code>forall xf g. renderD (xf *% g) == xf *%% renderD g
</code></pre>

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

<pre><code>type RenderingDX = Transform3 -&gt; RenderingD

renderDX :: (Ord d, Bounded d) =&gt; Geometry -&gt; RenderingDX d
</code></pre>

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

<pre><code>renderDX g xf == renderD (xf *% g)
</code></pre>

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

<pre><code>renderD g == renderDX g identityX
</code></pre>

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

<pre><code>renderDX (xfi *% g)

  == {- specification of renderDX -}

 xfo -&gt; renderD (xfo *% (xfi *% g))

  == {- property of transformation -}

 xfo -&gt; renderD ((xfo `composeX` xfi) *% g)

  == {- specification of renderDX  -}

 xfo -&gt; renderDX g (xfo `composeX` xfi)
</code></pre>

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

<pre><code>renderDX mempty

  == {- specification of renderDX -}

 xf -&gt; renderD (xf *% mempty)

  == {- property of (*%) and mempty -}

 xf -&gt; renderD mempty

  == {- renderD is a monoid morphism -}

 xf -&gt; mempty

  == {- definition of pure on functions -}

pure mempty

  == {- definition of mempty on functions -}

mempty
</code></pre>

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

<pre><code>renderDX (ga `mappend` gb)

  == {- specification of renderDX -}

 xf -&gt; renderD (xf *% (ga `mappend` gb))

  == {- property of transformation and union -}

 xf -&gt; renderD ((xf *% ga) `mappend` (xf *% gb))

  == {- renderD is a monoid morphism -}

 xf -&gt; renderD (xf *% ga) `mappend` renderD (xf *% gb)

  == {- specification of renderDX  -}

 xf -&gt; renderDX ga xf `mappend` renderDX gb xf

  == {- definition of liftA2/(&lt;*&gt;) on functions -}

liftA2 mappend (renderDX ga) (renderDX gb)

  == {- definition of mappend on functions -}

renderDX ga `mappend` renderDX gb
</code></pre>

<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>
<p><a href="http://conal.net/blog/?flattrss_redirect&amp;id=75&amp;md5=a47ae6e1e1a51016836d913e562dbd3e"><img src="http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png" srcset="http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png, http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white@2x.png 2xhttp://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png, http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white@3x.png 3x" alt="Flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/3d-rendering-as-functional-reactive-programming/feed</wfw:commentRss>
		<slash:comments>11</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=conal&amp;popout=1&amp;url=http%3A%2F%2Fconal.net%2Fblog%2Fposts%2F3d-rendering-as-functional-reactive-programming&amp;language=en_GB&amp;category=text&amp;title=3D+rendering+as+functional+reactive+programming&amp;description=I%26%238217%3Bve+been+playing+with+a+simple%2Fgeneral+semantics+for+3D.+In+the+process%2C+I+was+surprised+to+see+that+a+key+part+of+the+semantics+looks+exactly+like+a+key+part...&amp;tags=3D%2CFRP%2Cfunctional+reactive+programming%2Cmonoid%2Csemantics%2Cblog" type="text/html" />
	</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><![CDATA[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>
		<category><![CDATA[zipper]]></category>

		<guid isPermaLink="false">http://conal.net/blog/?p=67</guid>
		<description><![CDATA[The post Sequences, streams, and segments offered an answer to the the question of what&#8217;s missing in the following box: infinitefinite discreteStream Sequence continuousFunction ??? I presented a simple type of function segments, whose representation contains a length (duration) and a function. This type implements most of the usual classes: Monoid, Functor, Zip, and Applicative, [&#8230;]]]></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, zipper

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>
<li>2011-08-18: Eliminated accidental emoticon in the definition of <code>dup</code>, thanks to anonymous.</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>

<pre><code>data t :-&gt;# a = FS t (t -&gt; a)
</code></pre>

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

<pre><code>instance (Ord t, Num t) =&gt; Monoid (t :-&gt;# a) where
    mempty = FS 0 (error "sampling empty 't :-&gt;# a'")
    FS c f `mappend` FS d g =
      FS (c + d) ( t -&gt; if t &lt;= c then f t else g (t - c))
</code></pre>

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

<pre><code>-- | Signal indexed by t with values of type a.
newtype t :-&gt; a = S { unS :: [t :-&gt;# a] }
</code></pre>

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

<pre><code>meaning :: (Ord t, Num t) =&gt; (t :-&gt; a) -&gt; (t :-&gt;# a)
meaning = mconcat . unS
</code></pre>

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

<pre><code>inS  :: ([s :-&gt;# a] -&gt; [t :-&gt;# b])
     -&gt; ((s :-&gt;  a) -&gt; (t :-&gt;  b))

inS2 :: ([s :-&gt;# a] -&gt; [t :-&gt;# b] -&gt; [u :-&gt;# c])
     -&gt; ((s :-&gt;  a) -&gt; (t :-&gt;  b) -&gt; (u :-&gt;  c))
</code></pre>

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

<pre><code>inS  = result   S . argument unS
inS2 = result inS . argument unS
</code></pre>

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

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

<pre><code>instance Functor ((:-&gt;) t) where
    fmap h (S ss) = S (fmap (fmap h) ss)
</code></pre>

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

<pre><code>instance Functor ((:-&gt;) t) where
    fmap = inS . fmap . fmap
</code></pre>

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

<pre><code> meaning . fmap h == fmap h . meaning
</code></pre>

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

<pre><code>meaning . fmap h 

  == {- fmap definition -}

meaning . S . fmap (fmap h) . unS

  == {- meaning definition -}

mconcat . unS . S . fmap (fmap h) . unS

  == {- unS and S are inverses  -}

mconcat . fmap (fmap h) . unS

  == {- fmap h distributes over mappend -}

fmap h . mconcat . unS

  == {- meaning definition -}

fmap . meaning
</code></pre>

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

<pre><code>meaning (pure a)    == pure a
meaning (bf &lt;*&gt; bx) == meaning bf &lt;*&gt; meaning bx
</code></pre>

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

<pre><code>instance (Ord t, Num t, Bounded t) =&gt; Applicative ((:-&gt;) t) where
    pure  = S . pure . pure
    (&lt;*&gt;) = inS2 appl

appl :: (Ord t, Num t, Bounded t) =&gt;
        [t :-&gt;# (a -&gt; b)] -&gt; [t :-&gt;# a] -&gt; [t :-&gt;# b]
</code></pre>

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

<pre><code>[] `appl` _  = []

_  `appl` [] = []
</code></pre>

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

<pre><code>(fs:fss') `appl` (xs:xss')
   | fd == xd  = (fs  &lt;*&gt; xs ) : (fss' `appl`       xss' )
   | fd &lt;  xd  = (fs  &lt;*&gt; xs') : (fss' `appl` (xs'':xss'))
   | otherwise = (fs' &lt;*&gt; xs ) : ((fs'':fss') `appl` xss')
 where
   fd         = length fs
   xd         = length xs
   (fs',fs'') = splitAt xd fs
   (xs',xs'') = splitAt fd xs
</code></pre>

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

<pre><code>instance (Ord t, Num t, Bounded t) =&gt; Zip ((:-&gt;) t) where zip = liftA2 (,)
</code></pre>

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

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

<pre><code>instance Monoid (t :-&gt; a) where
  mempty = S []
  S xss `mappend` S yss = S (xss ++ yss)
</code></pre>

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

<pre><code>instance Monoid (t :-&gt; a) where
    mempty  = S mempty
    mappend = inS2 mappend
</code></pre>

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

<pre><code>class Segment seg dur | seg -&gt; dur where
    null    :: seg -&gt; Bool
    length  :: seg -&gt; dur
    take    :: dur -&gt; seg -&gt; seg
    drop    :: dur -&gt; seg -&gt; seg
    splitAt :: dur -&gt; seg -&gt; (seg,seg)
    -- Defaults:
    splitAt d s = (take d s, drop d s)
    take    d s = fst (splitAt d s)
    drop    d s = snd (splitAt d s)
</code></pre>

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

<pre><code>instance (Ord t, Num t) =&gt; Segment (t :-&gt; a) t where
  null   (S xss) = null xss
  length (S xss) = sum (length &lt;$&gt; xss)
  ...
</code></pre>

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

<pre><code>  -- Alternative definition
  null (S xss) = all null xss
</code></pre>

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

<pre><code>  splitAt _ (S [])  = (mempty,mempty)
  splitAt d b | d &lt;= 0 = (mempty, b)
  splitAt d (S (xs:xss')) =
    case (d `compare` xd) of
      EQ -&gt; (S [xs], S xss')
      LT -&gt; let (xs',xs'') = splitAt d xs in
              (S [xs'], S (xs'':xss'))
      GT -&gt; let (S uss, suffix) = splitAt (d-xd) (S xss') in
              (S (xs:uss), suffix)
   where
     xd = length xs
</code></pre>

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

<pre><code>instance Num t =&gt; Copointed ((:-&gt;) t) where
    extract (S [])     = error "extract: empty S"
    extract (S (xs:_)) = extract xs
</code></pre>

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

<pre><code>-- Alternative definition
instance Num t =&gt; Copointed ((:-&gt;) t) where
    extract (S []) = error "extract: empty S"
    extract (S (xs:xss'))
      | null xs     = extract (S xss')
      | otherwise   = extract xs
</code></pre>

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

<pre><code>instance Num t =&gt; Copointed ((:-&gt;) t) where
    extract = extract . extract . unS
</code></pre>

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

<pre><code>duplicate :: (t :-&gt; a) -&gt; (t :-&gt; (t :-&gt; a))
</code></pre>

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

<pre><code>instance (Ord t, Num t) =&gt; Comonad ((:-&gt;) t) where
    duplicate = fmap S . inS dup
</code></pre>

<p>with content part:</p>

<pre><code>dup :: (Ord t, Num t) =&gt; [t :-&gt;# a] -&gt; [t :-&gt;# [t :-&gt;# a]]
</code></pre>

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

<pre><code>dup []        = []

dup (xs:xss') = ((: xss') &lt;$&gt; duplicate xs) : dup xss'
</code></pre>

<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 non-monotonic 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>
<p><a href="http://conal.net/blog/?flattrss_redirect&amp;id=67&amp;md5=e15e8c9dfd9e8f9c0aadd8dc805515dc"><img src="http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png" srcset="http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png, http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white@2x.png 2xhttp://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png, http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white@3x.png 3x" alt="Flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/sequences-segments-and-signals/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=conal&amp;popout=1&amp;url=http%3A%2F%2Fconal.net%2Fblog%2Fposts%2Fsequences-segments-and-signals&amp;language=en_GB&amp;category=text&amp;title=Sequences%2C+segments%2C+and+signals&amp;description=The+post+Sequences%2C+streams%2C+and+segments+offered+an+answer+to+the+the+question+of+what%26%238217%3Bs+missing+in+the+following+box%3A+infinitefinite+discreteStream+Sequence+continuousFunction+%3F%3F%3F+I+presented+a+simple+type...&amp;tags=applicative+functor%2Ccomonad%2CFRP%2Cfunction%2Cfunctional+reactive+programming%2Cfunctor%2Cmonoid%2Csegment%2Csequence%2Ctype+class+morphism%2Czipper%2Cblog" type="text/html" />
	</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><![CDATA[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[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 flow [&#8230;]]]></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>

<pre><code>data Stream a = Cons a (Stream a)
</code></pre>

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

<pre><code>instance Functor Stream where
    fmap f (Cons x xs) = Cons (f x) (fmap f xs)

instance Applicative Stream where
    pure  = repeat
    (&lt;*&gt;) = zipWith ($)

repeat :: a -&gt; Stream a
repeat x = Cons x (repeat x)
</code></pre>

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

<pre><code>return  :: Monad m     =&gt; a -&gt; m a
</code></pre>

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

<pre><code>extract :: Copointed w =&gt; w a -&gt; a
</code></pre>

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

<pre><code>a -&gt; m b
</code></pre>

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

<pre><code>w a -&gt; b
</code></pre>

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

<pre><code>(=&lt;&lt;) :: (Monad m) =&gt; (a -&gt; m b) -&gt; (m a -&gt; m b)
</code></pre>

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

<pre><code>(&gt;&gt;=) :: (Monad m) =&gt; m a -&gt; (a -&gt; m b) -&gt; m b
</code></pre>

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

<pre><code>extend :: (Comonad w) =&gt; (w a -&gt; b) -&gt; (w a -&gt; w b)
</code></pre>

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

<pre><code>(=&gt;&gt;) :: (Comonad w) =&gt; w a -&gt; (w a -&gt; b) -&gt; w b
</code></pre>

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

<pre><code>join      :: (Monad   m) =&gt; m (m a) -&gt; m a
</code></pre>

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

<pre><code>duplicate :: (Comonad w) =&gt; w a -&gt; w (w a)
</code></pre>

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

<pre><code>head :: Stream a -&gt; a
head (Cons x _ ) = x

tails :: Stream a -&gt; Stream (Stream a)
tails xs = Cons xs (tails (tail xs))
</code></pre>

<p>where</p>

<pre><code>tail :: Stream a -&gt; Stream a
tail (Cons _ xs) = xs
</code></pre>

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

<pre><code>instance Copointed Stream where extract   = head
instance Comonad   Stream where duplicate = tails
</code></pre>

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

<pre><code>class Monoid o where
    mempty  :: o
    mappend :: o -&gt; o -&gt; o
</code></pre>

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

<pre><code>class Segment seg len where
    length :: seg -&gt; len
    drop   :: len -&gt; seg -&gt; seg
    take   :: len -&gt; seg -&gt; seg
</code></pre>

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

<pre><code>instance Segment [a] Int where
    length = Prelude.length
    drop   = Prelude.drop
    take   = Prelude.take
</code></pre>

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

<pre><code>instance Integral i =&gt; Segment [a] i where
    length = genericLength
    drop   = genericDrop
    take   = genericTake
</code></pre>

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

<pre><code>drop (length as) (as `mappend` bs) == bs
take (length as) (as `mappend` bs) == as

t &lt;= length as ==&gt; length (take t as) == t
t &lt;= length as ==&gt; length (drop t as) == length as - t
</code></pre>

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

<pre><code>instance Functor ((-&gt;) t) where
    fmap = (.)

instance Applicative ((-&gt;) t) where
    pure = const
    (f &lt;*&gt; g) x = (f x) (g x)

instance Monad ((-&gt;) t) where
    return = const
    f &gt;&gt;= k =  t -&gt; k (f t) t
</code></pre>

<p>As a consequence,</p>

<pre><code>  join f == f &gt;&gt;= id ==  t -&gt; f t t
</code></pre>

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

<pre><code>instance Monoid o =&gt; Copointed ((-&gt;) o) where
    extract f = f mempty

instance Monoid o =&gt; Comonad ((-&gt;) o) where
    duplicate f x =  y -&gt; f (x `mappend` y)
</code></pre>

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

<pre><code>data t :-&gt;# a = FS t (t -&gt; a)
</code></pre>

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

<pre><code>instance (Ord t, Num t) =&gt; Monoid (t :-&gt;# a) where
    mempty = FS 0 (error "sampling empty 't :-&gt;# a'")
    FS c f `mappend` FS d g =
      FS (c + d) ( t -&gt; if t &lt;= c then f t else g (t - c))
</code></pre>

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

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

<pre><code>instance Num t =&gt; Segment (t :-&gt;# a) t where
    length (FS d _) = d
    drop t (FS d f) = FS (d - t) ( t' -&gt; f (t + t'))
    take t (FS _ f) = FS t f
</code></pre>

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

<pre><code>instance Functor ((:-&gt;#) t) where
    fmap h (FS d f) = FS d (h . f)
</code></pre>

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

<pre><code>instance Ord t =&gt; Zip ((:-&gt;#) t) where
    FS xd xf `zip` FS yd yf = FS (xd `min` yd) (xf `zip` yf)
</code></pre>

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

<pre><code>instance (Ord t, Bounded t) =&gt; Applicative ((:-&gt;#) t) where
    pure a = FS maxBound (const a)
    (&lt;*&gt;)  = zipWith ($)
</code></pre>

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

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

<pre><code>instance Num t =&gt; Copointed ((:-&gt;#) t) where
    extract (FS _ f) = f 0
</code></pre>

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

<pre><code>instance Num t =&gt; Comonad ((:-&gt;#) t) where
    duplicate s = FS (length s) (flip drop s)
</code></pre>

<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>
<p><a href="http://conal.net/blog/?flattrss_redirect&amp;id=65&amp;md5=844ce48c997f35fb216e2d03108a8a21"><img src="http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png" srcset="http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png, http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white@2x.png 2xhttp://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png, http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white@3x.png 3x" alt="Flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/sequences-streams-and-segments/feed</wfw:commentRss>
		<slash:comments>13</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=conal&amp;popout=1&amp;url=http%3A%2F%2Fconal.net%2Fblog%2Fposts%2Fsequences-streams-and-segments&amp;language=en_GB&amp;category=text&amp;title=Sequences%2C+streams%2C+and+segments&amp;description=What+kind+of+thing+is+a+movie%3F+Or+a+song%3F+Or+a+trajectory+from+point+A+to+point+B%3F+If+you%26%238217%3Bre+a+computer+programmer%2Fprogrammee%2C+you+might+say+that+such+things...&amp;tags=applicative+functor%2Ccomonad%2CFRP%2Cfunction%2Cfunctional+reactive+programming%2Cfunctor%2Cmonoid%2Csequence%2Cblog" type="text/html" />
	</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><![CDATA[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[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 &#38; Ross Paterson introduced us to applicative functors, and I remembered using that pattern to reduce all of the [&#8230;]]]></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>

<pre><code>type B a = Time -&gt; a

at :: Behavior a -&gt; B a
</code></pre>

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

<pre><code>at time == id
</code></pre>

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

<pre><code>instance Functor Behavior where ...
</code></pre>

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

<pre><code>  fmap f b `at` t == f (b `at` t)
</code></pre>

<p>Equivalently,</p>

<pre><code>  at (fmap f b) ==  t -&gt; f (b `at` t)
                == f . ( t -&gt; b `at` t)
                == f . at b
</code></pre>

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

<pre><code>instance Functor ((-&gt;) t) where fmap = (.)
</code></pre>

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

<pre><code>  at (fmap f b) == fmap f (at b)
</code></pre>

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

<pre><code>  at . fmap f == fmap f . at
</code></pre>

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

<pre><code>infixl 4 &lt;*&gt;
class Functor f =&gt; Applicative f where
  pure  :: a -&gt; f a
  (&lt;*&gt;) :: f (a-&gt;b) -&gt; f a -&gt; f b
</code></pre>

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

<pre><code>liftA3 :: Applicative f =&gt;
          (  a -&gt;   b -&gt;   c -&gt;   d)
       -&gt;  f a -&gt; f b -&gt; f c -&gt; f d
liftA3 h fa fb fc = pure h &lt;*&gt; fa &lt;*&gt; fb &lt;*&gt; fc
</code></pre>

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

<pre><code>at (fb &lt;*&gt; xb) ==  t -&gt; (fb `at` t) (xb `at` t)
</code></pre>

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

<pre><code>at (pure a) ==  t -&gt; a
            == const a
</code></pre>

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

<pre><code>instance Applicative ((-&gt;) t) where
  pure a    = const a
  hf &lt;*&gt; xf =  t -&gt; (hf t) (xf t)
</code></pre>

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

<pre><code>at (pure a)    == pure a
at (fb &lt;*&gt; xb) == at fb &lt;*&gt; at xb
</code></pre>

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

<pre><code>nu . join == join . nu . fmap nu
</code></pre>

<p>where</p>

<pre><code>join :: Monad m =&gt; m (m a) -&gt; m a
</code></pre>

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

<pre><code>at (return a) == return a
at (join bb)  == join (at (fmap at bb))
</code></pre>

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

<pre><code>fmap h f == h . f
join f   ==  t -&gt; f t t
</code></pre>

<p>the second condition is</p>

<pre><code>at (join bb) == join (at (fmap at bb))
             ==  t -&gt; at (at . bb) t t
             ==  t -&gt; at (at bb t) t
             ==  t -&gt; (bb `at` t) `at` t
</code></pre>

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

<pre><code>occs (e `mappend` e') == occs e `merge` occs e'
</code></pre>

<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>
<p><a href="http://conal.net/blog/?flattrss_redirect&amp;id=23&amp;md5=1da841eb36a6131cb61d906442f69326"><img src="http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png" srcset="http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png, http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white@2x.png 2xhttp://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png, http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white@3x.png 3x" alt="Flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/simplifying-semantics-with-type-class-morphisms/feed</wfw:commentRss>
		<slash:comments>18</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=conal&amp;popout=1&amp;url=http%3A%2F%2Fconal.net%2Fblog%2Fposts%2Fsimplifying-semantics-with-type-class-morphisms&amp;language=en_GB&amp;category=text&amp;title=Simplifying+semantics+with+type+class+morphisms&amp;description=When+I+first+started+playing+with+functional+reactivity+in+Fran+and+its+predecessors%2C+I+didn%26%238217%3Bt+realize+that+much+of+the+functionality+of+events+and+reactive+behaviors+could+be+packaged+via...&amp;tags=applicative+functor%2CFRP%2Cfunctional+reactive+programming%2Cfunctor%2Cmonad%2Cmonoid%2Csemantics%2Ctype+class%2Ctype+class+morphism%2Cblog" type="text/html" />
	</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><![CDATA[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[I submitted a paper Simply efficient functional reactivity to ICFP 2008. Abstract: 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 [&#8230;]]]></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 -->
<p><a href="http://conal.net/blog/?flattrss_redirect&amp;id=22&amp;md5=dee648d38383131c59963d5b9b4c4b93"><img src="http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png" srcset="http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png, http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white@2x.png 2xhttp://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png, http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white@3x.png 3x" alt="Flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/simply-efficient-functional-reactivity/feed</wfw:commentRss>
		<slash:comments>33</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=conal&amp;popout=1&amp;url=http%3A%2F%2Fconal.net%2Fblog%2Fposts%2Fsimply-efficient-functional-reactivity&amp;language=en_GB&amp;category=text&amp;title=Simply+efficient+functional+reactivity&amp;description=I+submitted+a+paper+Simply+efficient+functional+reactivity+to+ICFP+2008.+Abstract%3A+Functional+reactive+programming+%28FRP%29+has+simple+and+powerful+semantics%2C+but+has+resisted+efficient+implementation.+In+particular%2C+most+past...&amp;tags=applicative+functor%2Ccontinuous%2Cdiscrete%2Cevents%2CFRP%2Cfunctional+reactive+programming%2Cfunctor%2Cfuture+value%2Cicfp%2Cimplementation%2CjoinMaybes%2Cmonad%2Cmonoid%2Cmulti-threading%2Cnormal+form%2Cpaper%2Creactive+behavior%2Creactive+value%2Csemantics%2Ctime%2Ctype+class%2Ctype+class+morphism%2Ctype+composition%2Cblog" type="text/html" />
	</item>
		<item>
		<title>Functional reactive chatter-bots</title>
		<link>http://conal.net/blog/posts/functional-reactive-chatter-bots</link>
		<comments>http://conal.net/blog/posts/functional-reactive-chatter-bots#comments</comments>
		<pubDate>Wed, 06 Feb 2008 06:22:26 +0000</pubDate>
		<dc:creator><![CDATA[Conal]]></dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[applicative functor]]></category>
		<category><![CDATA[arrow]]></category>
		<category><![CDATA[bot]]></category>
		<category><![CDATA[chatter-bot]]></category>
		<category><![CDATA[FRP]]></category>
		<category><![CDATA[functional reactive programming]]></category>
		<category><![CDATA[functor]]></category>
		<category><![CDATA[monoid]]></category>
		<category><![CDATA[mutant]]></category>

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

Title: Functional reactive chatter-bots

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

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

-->

<!-- references -->

<!-- teaser -->

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

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

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

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

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

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

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

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

<h2>Stream-bots</h2>

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

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

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

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

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

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

<h2>Other classes</h2>

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

<h3>Functor and Applicative</h3>

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

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

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

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

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

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

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

<h3>Monad</h3>

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

<h3>Monoid</h3>

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

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

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

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

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

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

<h2>Mutant-bots</h2>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

<h2>Choosy bots</h2>

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

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

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

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

<h2>Cooperation and disagreements</h2>

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

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

<h2>Chatter-bots</h2>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

<h2>Filtering</h2>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		<guid isPermaLink="false">http://conal.net/blog/posts/future-values-part-two-a-multi-threaded-implementation/</guid>
		<description><![CDATA[Future values A previous post described future values (or simply &#8220;futures&#8221;), which are values depend on information from the future, e.g., from the real world. There I gave a simple denotational semantics for future values as time/value pairs. This post describes the multi-threaded implementation of futures in Reactive&#8216;s Data.Reactive module. A simple representation Futures are [&#8230;]]]></description>
				<content:encoded><![CDATA[<!-- 

Title Future values via multi-threading

Tags: future values, multi-threading, implementation, functors, applicative functors, monads, monoids

-->

<!-- References -->

<h2>Future values</h2>

<p>A <a href="http://conal.net/blog/posts/future-values/" title="Blog post: &quot;Future values&quot;">previous post</a> described future values (or simply &#8220;futures&#8221;), which are values depend on information from the future, e.g., from the real world. There I gave a simple denotational semantics for future values as time/value pairs.  This post describes the multi-threaded implementation of futures in <a href="http://haskell.org/haskellwiki/Reactive" title="Wiki page for the Reactive library">Reactive</a>&#8216;s <code>Data.Reactive</code> module.</p>

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

<h2>A simple representation</h2>

<p>Futures are represented as actions that deliver a value.  These actions are required to yield the same answer every time.   Having a special representation for the future that never arrives (<code>mempty</code>) will allow for some very important optimizations later.</p>

<pre><code>data Future a = Future (IO a) | Never
</code></pre>

<p>A value can be &#8220;forced&#8221; from a future.  If the value isn&#8217;t yet available, forcing will block.</p>

<pre><code>force :: Future a -&gt; IO a
force (Future io) = io
force Never       = hang  -- block forever
</code></pre>

<h2>Threads and synchronization</h2>

<p>The current implementation of futures uses <a href="http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Concurrent.html">Concurrent Haskell</a>&#8216;s <code>forkIO</code>
(fork a thread) and <code>MVar</code>s (synchronized communication variables).</p>

<p>Except for trivial futures (<code>pure</code>/<code>return</code> and <code>mempty</code>), the action in a future will simply be reading an MVar.  Internal to the implementation:</p>

<pre><code>newFuture :: IO (Future a, a -&gt; IO ())
newFuture = do v &lt;- newEmptyMVar
               return (Future (readMVar v), putMVar v)
</code></pre>

<p>The MVar is written to as the final step of a forked thread.  Importantly, it is to be written only once.  (It&#8217;s really an IVar.)</p>

<pre><code>future :: IO a -&gt; Future a
future mka = unsafePerformIO $
             do (fut,sink) &lt;- newFuture
                forkIO $ mka &gt;&gt;= sink
                return fut
</code></pre>

<p>Note that the actual value is computed just once, and is accessed cheaply.</p>

<h2>Functor, Applicative, and Monad</h2>

<p>The <code>Functor</code>, <code>Applicative</code>, and <code>Monad</code> instances are defined easily in terms of <code>future</code> and the corresponding instances for <code>IO</code>:</p>

<pre><code>instance Functor Future where
  fmap f (Future get) = future (fmap f get)
  fmap _ Never        = Never

instance Applicative Future where
  pure a                      = Future (pure a)
  Future getf &lt;*&gt; Future getx = future (getf &lt;*&gt; getx)
  _           &lt;*&gt; _           = Never

instance Monad Future where
  return            = pure
  Future geta &gt;&gt;= h = future (geta &gt;&gt;= force . h)
  Never       &gt;&gt;= _ = Never
</code></pre>

<h2>Monoid &#8212; racing</h2>

<p>The remaining class to implement is <code>Monoid</code>.  The <code>mempty</code> method is <code>Never</code>.  The <code>mappend</code> method is to select the earlier of two futures, which is implemented by having the two futures race to extrat a value:</p>

<pre><code>instance Monoid (Future a) where
  mempty  = Never
  mappend = race

race :: Future a -&gt; Future a -&gt; Future a
</code></pre>

<p>Racing is easy in the case either is <code>Never</code>:</p>

<pre><code>Never `race` b     = b
a     `race` Never = a
</code></pre>

<p>Otherwise, spin a thread for each future.  The winner kills the loser.</p>

<pre><code>a `race` b = unsafePerformIO $
             do (c,sink) &lt;- newFuture
                let run fut tid = forkIO $ do x &lt;- force fut
                                              killThread tid
                                              sink x
                mdo ta &lt;- run a tb
                    tb &lt;- run b ta
                    return ()
                return c
</code></pre>

<h2>The problem</h2>

<p>This last piece of the implementation can fall short of the semantics.  For <code>a `mappend` b</code>, we might get <code>b</code> instead of <code>a</code> even if they&#8217;re available simultaneously.  It&#8217;s even possible to get the later of the two if they&#8217;re nearly simultaneous.</p>

<p><em>Edit (2008-02-02)</em>: although simultaneous <em>physical</em> events are extremely unlikely, futures are compositional, so it&#8217;s easy to construct two distinct but simultaneous futures in terms of on a common physical future.</p>

<p>What will it take to get deterministic semantics for <code>a `mappend` b</code>?  Here&#8217;s an idea: include an  explicit time in a future.  When one future happens with a time <code>t</code>, query whether the other one occurs by the same time.  What does it take to support this query operation?</p>

<h2>A simpler implementation</h2>

<p>In this implementation, futures (other than <code>Never</code>) hold actions that typically read an MVar that is written only once.  They could instead simply hold lazy values.</p>

<pre><code>data Future a = Future a | Never
</code></pre>

<p>Forcing a future evaluates to weak head normal form (WHNF).</p>

<pre><code>force :: Future a -&gt; IO a
force (Future a) = a `seq` return a
force Never      = hang
</code></pre>

<p>Making new future would work almost identically, just adding an <code>unsafePerformIO</code>.</p>

<pre><code>newFuture :: IO (Future a, a -&gt; IO ())
newFuture = 
  do v &lt;- newEmptyMVar
     return (Future (unsafePerformIO $ readMVar v), putMVar v)
</code></pre>

<p>The <code>Functor</code>, <code>Applicative</code>, and <code>Monad</code> instances simplify considerably, using function application directly, instead of the corresponding methods from the <code>Functor</code>, <code>Applicative</code>, and <code>Monad</code> instances of <code>IO</code>.</p>

<pre><code>instance Functor Future where
  fmap f (Future a) = Future (f a)
  fmap _ Never      = Never

instance Applicative Future where
  pure a                = Future a
  Future f &lt;*&gt; Future x = Future (f x)
  _        &lt;*&gt; _        = Never

instance Monad Future where
  return         = pure
  Future a &gt;&gt;= h = h a
  Never    &gt;&gt;= _ = Never
</code></pre>

<p>The <code>Monoid</code> instance is completely unchanged.</p>

<p>How does this implementation compare with the one above?</p>

<ul>
<li>It&#8217;s simpler, as stated.</li>
<li>It&#8217;s a bit more efficient.  Each MVar is only read once.  Also, the <code>Functor</code>, <code>Applicative</code>, and <code>Monad</code> instances no longer create threads and MVars.</li>
<li>The type statically enforces that forcing a future always gives the same result.</li>
<li>Forcing a future reduces the value to WHNF and so is probably a little less lazy than the  implementation above.</li>
</ul>

<p>I&#8217;ve tried out this implementation and found that it intermittently crashes some examples that work fine in the <code>IO</code> version.  I have no idea why, and I&#8217;d be very interested in ideas about it or anything else in this post.</p>
<p><a href="http://conal.net/blog/?flattrss_redirect&amp;id=8&amp;md5=1d95c4fec83fe61459b536348c3e2ffe"><img src="http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png" srcset="http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png, http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white@2x.png 2xhttp://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png, http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white@3x.png 3x" alt="Flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/future-values-via-multi-threading/feed</wfw:commentRss>
		<slash:comments>10</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=conal&amp;popout=1&amp;url=http%3A%2F%2Fconal.net%2Fblog%2Fposts%2Ffuture-values-via-multi-threading&amp;language=en_GB&amp;category=text&amp;title=Future+values+via+multi-threading&amp;description=Future+values+A+previous+post+described+future+values+%28or+simply+%26%238220%3Bfutures%26%238221%3B%29%2C+which+are+values+depend+on+information+from+the+future%2C+e.g.%2C+from+the+real+world.+There+I+gave+a+simple...&amp;tags=applicative+functor%2Cfunctor%2Cfuture+value%2Cimplementation%2Cmonad%2Cmonoid%2Cmulti-threading%2Cblog" type="text/html" />
	</item>
		<item>
		<title>Future values</title>
		<link>http://conal.net/blog/posts/future-values</link>
		<comments>http://conal.net/blog/posts/future-values#comments</comments>
		<pubDate>Wed, 16 Jan 2008 01:31:00 +0000</pubDate>
		<dc:creator><![CDATA[Conal]]></dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[applicative functor]]></category>
		<category><![CDATA[future value]]></category>
		<category><![CDATA[monad]]></category>
		<category><![CDATA[monoid]]></category>
		<category><![CDATA[semantics]]></category>
		<category><![CDATA[type class]]></category>

		<guid isPermaLink="false">http://conal.net/blog/posts/future-values-part-one-semantics/</guid>
		<description><![CDATA[A future value (or simply &#8220;future&#8221;) is a value that might not be knowable until a later time, such as &#8220;the value of the next key you press&#8221;, or &#8220;the value of LambdaPix stock at noon next Monday&#8221; (both from the time you first read this sentence), or &#8220;how many tries it will take me [&#8230;]]]></description>
				<content:encoded><![CDATA[<!-- 

Title: Future values

Tags: applicative functors, future values, monads, monoids, semantics, reactivity

-->

<!-- References -->

<!-- teaser -->

<p>A <em>future value</em> (or simply &#8220;future&#8221;) is a value that might not be knowable until a later time, such as &#8220;the value of the next key you press&#8221;, or &#8220;the value of LambdaPix stock at noon next Monday&#8221; (both from the time you first read this sentence), or &#8220;how many tries it will take me to blow out all the candles on my next birthday cake&#8221;.  Unlike an imperative computation, each future has a unique value &#8212; although you probably cannot yet know what that value is.  I&#8217;ve implemented this notion of futures as part of a library <a href="http://haskell.org/haskellwiki/Reactive" title="Reactive">Reactive</a>.</p>

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

<ul>
<li>2008-04-04: tweaked tag; removed first section heading.</li>
</ul>

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

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

<p>You can <em>force</em> a future, which makes you wait (block) until its value is knowable.  Meanwhile, what kinds of things can you do a future <em>now</em>?</p>

<ul>
<li>Apply a function to the not-yet-known value, resulting in another future.  For instance, suppose <code>fc :: Future Char</code> is the first character you type after a specific time.  Then <code>fmap toUpper fc :: Future Char</code> is the capitalized version of the future character.  Thus, <code>Future</code> is a functor.  The resulting future is knowable when <code>fc</code> is knowable.</li>
<li>What about combining two or more future values?  For instance, how many days between the first time after the start of 2008 that the temperature exceeds 80 degrees Fahrenheit at (a) my home and (b) your home.  Each of those dates is a future value, and so is the difference between them.  If those futures are <code>m80, y80 :: Day</code>, then the difference is <code>diff80 = liftA2 (-) m80 y80</code>.  That difference is becomes knowable when the <em>later</em> of the <code>m80</code> and <code>y80</code> becomes knowable.  So <code>Future</code> is an applicative functor (AF), and one can apply a future function to a future argument to get a future result (<code>futRes = futFun &lt;*&gt; futArg</code>).  The other AF method is <code>pure :: a -&gt; Future a</code>, which makes a future value that is always knowable to be a given value.</li>
<li>Sometimes questions about the future are staged, such as &#8220;What will be the price of milk the day after it the temperature next drops below freezing&#8221; (plus specifics about where and starting when).  Suppose <code>priceOn :: Day -&gt; Future Price</code> gives the price of milk on a given day (at some specified place), and <code>nextFreeze :: Day -&gt; Future Day</code> is the first date of a freeze (also at a specified place) after a given date.  Then our query is expressed as <code>nextFreeze today &gt;&gt;= priceOn</code>, which has type <code>Future Price</code>.  <code>Future</code> is thus a monad.  (The <code>return</code> method of a monad is the same as the <code>pure</code> method of an AF.)  From another perspective on monads, we can collapse a future future into a future, using <code>join :: Future (Future a) -&gt; Future a</code>.</li>
</ul>

<p>These three ways of manipulating futures are all focused on the value of futures.  There is one more, very useful, combining operation that focuses on the <em>timing</em> of futures: given two futures, which one comes first.  Although we can&#8217;t know the answer now, we can ask the question now and get a future.  For example, what is the next character that either you or I will type?  Call those characters <code>mc, yc :: Future Char</code>.  The earlier of the two is <code>mc `mappend` yc</code>, which has type <code>Future Char</code>.  Thus, <code>Future ty</code> is a monoid for every type <code>ty</code>.  The other monoid method is <code>mempty</code> (the identity for <code>mappend</code>), which is the future that never happens.</p>

<h3>Why aren&#8217;t futures just lazy values?</h3>

<p>If futures were just lazy values, then we wouldn&#8217;t have to use <code>pure</code>, <code>fmap</code>, <code>(&lt;*&gt;)</code> (and <code>liftA</code>_n_), and <code>(&gt;&gt;=)</code>.  However, there isn&#8217;t enough semantic content in a plain-old-value to determine which of two values is <em>earlier</em> (<code>mappend</code> on futures).</p>

<h2>A semantics for futures</h2>

<p>To clarify my thinking about future values, I&#8217;d like to have a simple and precise denotational semantics and then an implementation that is faithful to the semantics.  The module <code>Data.SFuture</code> provides such a semantics, although the implementation in <code>Data.Future</code> is not completely faithful.</p>

<h3>The model</h3>

<p>The semantic model is very simple: (the meaning of) a future value is just a time/value pair.  The particular choice of &#8220;time&#8221; type is not important, as long as it is ordered.</p>

<pre><code>newtype Future t a = Future (Time t, a)
  deriving (Functor, Applicative, Monad, Show)
</code></pre>

<p>Delightfully, almost all required functionality comes automatically from the derived class instances, thanks to the standard instances for pairs and the definition of <code>Time</code>, given below.  Rather than require our time type to be bounded, we can easily add bounds to an arbitrary type.  Rather than defining <code>Time t</code> now, let&#8217;s discover the definition while considering the required meanings of the class instances.  The definition will use just a bit of wrapping around the type <code>t</code>, demonstrating a principle Conor McBride <a href="http://article.gmane.org/gmane.comp.lang.haskell.cafe/26520">expressed</a> as &#8220;types don&#8217;t just contain data, types explain data&#8221;.</p>

<h3>Functor</h3>

<p>The <code>Functor</code> instance is provided entirely by the standard instance for pairs:</p>

<pre><code>instance Functor ((,) a) where fmap f (a,b) = (a, f b)
</code></pre>

<p>In particular, <code>fmap f (Future (t,b)) == Future t (f b)</code>, as desired.</p>

<h3>Applicative and Time</h3>

<p>Look next at the <code>Applicative</code> instance for pairs:</p>

<pre><code>instance Monoid a =&gt; Applicative ((,) a) where
  pure x = (mempty, x)
  (u, f) &lt;*&gt; (v, x) = (u `mappend` v, f x)
</code></pre>

<p>So <code>Time t</code> must be a monoid, with <code>mempty</code> being the earliest time and <code>mappend</code> being <code>max</code>.  We&#8217;ll define <code>Time</code> with the help of the <code>Max</code> monoid:</p>

<pre><code>newtype Max a = Max { getMax :: a }
  deriving (Eq, Ord, Read, Show, Bounded)

instance (Ord a, Bounded a) =&gt; Monoid (Max a) where
  mempty = Max minBound
  Max a `mappend` Max b = Max (a `max` b)
</code></pre>

<p>We could require that the underlying time parameter type <code>t</code> be <code>Bounded</code>, but I want to have as few restrictions as possible.  For instance, <code>Integer</code>, <code>Float</code>, and <code>Double</code> are not <code>Bounded</code>, and neither are the types in the <code>Time</code> library.  Fortunately, it&#8217;s easy to add bounds to any type, preserving the existing ordering.</p>

<pre><code>data AddBounds a = MinBound | NoBound a | MaxBound
  deriving (Eq, Ord, Read, Show)

instance Bounded (AddBounds a) where
  minBound = MinBound
  maxBound = MaxBound
</code></pre>

<p>With these two reusable building blocks, our <code>Time</code> definition falls right out:</p>

<pre><code>type Time t = Max (AddBounds t)
</code></pre>

<h3>Monad</h3>

<p>For our <code>Monad</code> instance, we just need an instance for pairs equivalent to the Monad Writer instance.</p>

<pre><code>instance Monoid o =&gt; Monad ((,) o) where
  return = pure
  (o,a) &gt;&gt;= f = (o `mappend` o', a') where (o',a') = f a
</code></pre>

<p>Consequently (using <code>join m = m &gt;&gt;= id</code>), <code>join ((o, (o',a))) == (o `mappend` o', a)</code>.  Again, the standard instance implies exactly the desired meaning for futures.  <code>Future (t,a) &gt;&gt;= f</code> is available exactly at the later of <code>t</code> and the availability of <code>f a</code>.  We might have guessed instead that the time is simply the time of <code>f a</code>, e.g., assuming it to always be at least <code>t</code>.  However, <code>f a</code> could result from <code>pure</code> and so have time <code>minBound</code>.</p>

<h3>Monoid</h3>

<p>The last piece of <code>Future</code> functionality is the <code>Monoid</code> instance, and I don&#8217;t know how to get that instance to define itself.  I want <code>mappend</code> to yield the <em>earlier</em> of two futures, choosing the first argument when simultaneous.  The never-occuring <code>mempty</code> has a time beyond all <code>t</code> values.</p>

<pre><code>instance Ord t =&gt; Monoid (Future t a) where
  mempty  = Future (maxBound, error "it'll never happen, buddy")
  fut@(Future (t,_)) `mappend` fut'@(Future (t',_)) =
    if t &lt;= t' then fut else fut'
</code></pre>

<h2>Coming next</h2>

<p>Tune in for the <a href="http://conal.net/blog/posts/future-values-via-multi-threading/" title="Blog post: &quot;Future values via multi-threading&quot;">next post</a>, which describes the current implementation of future values in <a href="http://haskell.org/haskellwiki/Reactive" title="Reactive">Reactive</a>.  The implementation uses multi-threading and is not quite faithful to the semantics given here.  I&#8217;m looking for a faithful implementation.</p>

<p>A following post will then describe the use of future values in an elegant new implementation of functional reactive programming.</p>
<p><a href="http://conal.net/blog/?flattrss_redirect&amp;id=7&amp;md5=5180f9440be8fbe4e2084af47d4c3fd3"><img src="http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png" srcset="http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png, http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white@2x.png 2xhttp://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png, http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white@3x.png 3x" alt="Flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/future-values/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=conal&amp;popout=1&amp;url=http%3A%2F%2Fconal.net%2Fblog%2Fposts%2Ffuture-values&amp;language=en_GB&amp;category=text&amp;title=Future+values&amp;description=A+future+value+%28or+simply+%26%238220%3Bfuture%26%238221%3B%29+is+a+value+that+might+not+be+knowable+until+a+later+time%2C+such+as+%26%238220%3Bthe+value+of+the+next+key+you+press%26%238221%3B%2C+or+%26%238220%3Bthe...&amp;tags=applicative+functor%2Cfuture+value%2Cmonad%2Cmonoid%2Csemantics%2Ctype+class%2Cblog" type="text/html" />
	</item>
		<item>
		<title>A type for partial values</title>
		<link>http://conal.net/blog/posts/a-type-for-partial-values</link>
		<comments>http://conal.net/blog/posts/a-type-for-partial-values#comments</comments>
		<pubDate>Mon, 02 Jul 2007 00:47:00 +0000</pubDate>
		<dc:creator><![CDATA[Conal]]></dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[library]]></category>
		<category><![CDATA[monoid]]></category>
		<category><![CDATA[partial value]]></category>

		<guid isPermaLink="false">http://conal.net/blog/posts/a-type-for-partial-values/</guid>
		<description><![CDATA[In simplifying my Eros implementation, I came across a use for a type that represents partial information about values. I came up with a very simple implementation, though perhaps not quite ideal. In this post, I’ll present the interface and invite ideas for implementation. In the next post, I’ll give the implementation I use. First [&#8230;]]]></description>
				<content:encoded><![CDATA[<!-- 

Title: A type for partial values

Tags: Functional programming, Haskell, libraries, partial values

-->

<!-- references -->

<!-- teaser -->

<p>In simplifying my <a href="http://conal.net/papers/Eros">Eros</a> implementation, I came across a use for a type that represents partial information about values. I came up with a very simple implementation, though perhaps not quite ideal. In this post, I’ll present the interface and invite ideas for implementation. In the next post, I’ll give the implementation I use.</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-35"></span></p>

<p>First the type:</p>

<pre><code>type Partial a
</code></pre>

<p>I require that <code>Partial a</code> be a monoid, for which <code>mempty</code> is the completely undefined value, and in <code>u `mappend` v</code>, <code>v</code> selectively replaces parts of <code>u</code>. (Lattice-wise, <code>mempty</code> is bottom, and <code>mappend</code> is not quite <code>lub</code>, as it lacks commutativity).</p>

<p>Now the programming interface:</p>

<pre><code>-- Treat a full value as a partial one.  Fully overrides any "previous" (earlier
-- argument to mappend) partial value.
valp :: c -&gt; Partial c

-- Force a partial value into a full one, filling in bottom for any missing parts.
pval :: Partial c -&gt; c

-- Inverse to fst, on partial values.  Inject info into the the first half of a pair,
-- and leave the second half alone.
unFst :: Partial a -&gt; Partial (a,b)

-- Inverse to snd.
unSnd :: Partial b -&gt; Partial (a,b)

-- Inverse to "element" access, on all elements.  A way to inject some info about every
-- element.  For f, consider [], (-&gt;) a, Event, etc.
unElt :: Functor f =&gt; Partial a -&gt; Partial (f a)
</code></pre>

<p>That&#8217;s it. I&#8217;d love to hear ideas for representing Partial a and implementing the functions above. In the next post, I&#8217;ll give mine.</p>
<p><a href="http://conal.net/blog/?flattrss_redirect&amp;id=35&amp;md5=a93de6463362fec70d46d91900a24afa"><img src="http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png" srcset="http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png, http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white@2x.png 2xhttp://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white.png, http://conal.net/blog/wp-content/plugins/flattr/img/flattr-badge-white@3x.png 3x" alt="Flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://conal.net/blog/posts/a-type-for-partial-values/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=conal&amp;popout=1&amp;url=http%3A%2F%2Fconal.net%2Fblog%2Fposts%2Fa-type-for-partial-values&amp;language=en_GB&amp;category=text&amp;title=A+type+for+partial+values&amp;description=In+simplifying+my+Eros+implementation%2C+I+came+across+a+use+for+a+type+that+represents+partial+information+about+values.+I+came+up+with+a+very+simple+implementation%2C+though+perhaps+not...&amp;tags=library%2Cmonoid%2Cpartial+value%2Cblog" type="text/html" />
	</item>
	</channel>
</rss>
