<?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; monad</title>
	<atom:link href="http://conal.net/blog/tag/monad/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>Doing more with length-typed vectors</title>
		<link>http://conal.net/blog/posts/doing-more-with-length-typed-vectors</link>
		<comments>http://conal.net/blog/posts/doing-more-with-length-typed-vectors#comments</comments>
		<pubDate>Mon, 31 Jan 2011 01:16:09 +0000</pubDate>
		<dc:creator><![CDATA[Conal]]></dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[applicative functor]]></category>
		<category><![CDATA[monad]]></category>
		<category><![CDATA[number]]></category>
		<category><![CDATA[vector]]></category>

		<guid isPermaLink="false">http://conal.net/blog/?p=293</guid>
		<description><![CDATA[The post Fixing lists defined a (commonly used) type of vectors, whose lengths are determined statically, by type. In Vec n a, the length is n, and the elements have type a, where n is a type-encoded unary number, built up from zero and successor (Z and S). infixr 5 :&#60;data Vec &#8759; * &#8594; [&#8230;]]]></description>
				<content:encoded><![CDATA[<!-- teaser -->

<p
>The post <a href="http://conal.net/blog/posts/fixing-lists/" title="blog post"
  ><em
    >Fixing lists</em
    ></a
  > defined a (commonly used) type of vectors, whose lengths are determined statically, by type. In <code
  >Vec n a</code
  >, the length is <code
  >n</code
  >, and the elements have type <code
  >a</code
  >, where <code
  >n</code
  > is a type-encoded unary number, built up from zero and successor (<code
  >Z</code
  > and <code
  >S</code
  >).</p
>

<pre class="sourceCode haskell"
><code
  ><span class="kw"
    >infixr</span
    > <span class="dv"
    >5</span
    > <span class="fu"
    >:&lt;</span
    ><br
     /><br
     /><span class="kw"
    >data</span
    > <span class="dt"
    >Vec</span
    > <span class="dv"
    >&#8759;</span
    > <span class="fu"
    >*</span
    > &#8594; <span class="fu"
    >*</span
    > &#8594; <span class="fu"
    >*</span
    > <span class="kw"
    >where</span
    ><br
     />  <span class="dt"
    >ZVec</span
    > <span class="dv"
    >&#8759;</span
    >                <span class="dt"
    >Vec</span
    > <span class="dt"
    >Z</span
    >     a<br
     />  (<span class="fu"
    >:&lt;</span
    >) <span class="dv"
    >&#8759;</span
    > a &#8594; <span class="dt"
    >Vec</span
    > n a &#8594; <span class="dt"
    >Vec</span
    > (<span class="dt"
    >S</span
    > n) a<br
     /></code
  ></pre
>

<p
>It was fairly easy to define <code
  >foldr</code
  > for a <code
  >Foldable</code
  > instance, <code
  >fmap</code
  > for <code
  >Functor</code
  >, and <code
  >(&#8859;)</code
  > for <code
  >Applicative</code
  >. Completing the <code
  >Applicative</code
  > instance is tricky, however. Unlike <code
  >foldr</code
  >, <code
  >fmap</code
  >, and <code
  >(&#8859;)</code
  >, <code
  >pure</code
  > doesn't have a vector structure to crawl over. It must create just the right structure anyway. I left this challenge as a question to amuse readers. In this post, I give a few solutions, including my current favorite.</p
>

<p
>You can find the code for this post and the two <a href="http://conal.net/blog/posts/type-bounded-numbers/" title="blog post"
  >previous</a
  > <a href="http://conal.net/blog/posts/fixing-lists/" title="blog post"
  >ones</a
  > in a <a href="https://github.com/conal/numbers-vectors-trees/" title="github repository"
  >code repository</a
  >.</p
>

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

<div id="an-applicative-instance"
><h3
  >An Applicative instance</h3
  ><p
  >As a review, here is our <code
    >Functor</code
    > instance:</p
  ><pre class="sourceCode haskell"
  ><code
    ><span class="kw"
      >instance</span
      > <span class="kw"
      >Functor</span
      > (<span class="dt"
      >Vec</span
      > n) <span class="kw"
      >where</span
      ><br
       />  <span class="fu"
      >fmap</span
      > _ <span class="dt"
      >ZVec</span
      >     <span class="fu"
      >=</span
      > <span class="dt"
      >ZVec</span
      ><br
       />  <span class="fu"
      >fmap</span
      > f (a <span class="fu"
      >:&lt;</span
      > u) <span class="fu"
      >=</span
      > f a <span class="fu"
      >:&lt;</span
      > <span class="fu"
      >fmap</span
      > f u<br
       /></code
    ></pre
  ><p
  >And part of an <code
    >Applicative</code
    > instance:</p
  ><pre class="sourceCode haskell"
  ><code
    ><span class="kw"
      >instance</span
      > <span class="dt"
      >Applicative</span
      > (<span class="dt"
      >Vec</span
      > n) <span class="kw"
      >where</span
      ><br
       />  pure a <span class="fu"
      >=</span
      > <span class="fu"
      >??</span
      ><br
       />  <span class="dt"
      >ZVec</span
      >      &#8859; <span class="dt"
      >ZVec</span
      >      <span class="fu"
      >=</span
      > <span class="dt"
      >ZVec</span
      ><br
       />  (f <span class="fu"
      >:&lt;</span
      > fs) &#8859; (x <span class="fu"
      >:&lt;</span
      > xs) <span class="fu"
      >=</span
      > f x <span class="fu"
      >:&lt;</span
      > (fs &#8859; xs)<br
       /></code
    ></pre
  ><p
  >For <code
    >pure</code
    >, recall the troublesome goal signature:</p
  ><pre class="sourceCode haskell"
  ><code
    >  pure <span class="dv"
      >&#8759;</span
      > a &#8594; <span class="dt"
      >Vec</span
      > n a<br
       /></code
    ></pre
  ><p
  >There's at least one very good reason this type is problematic. The type <code
    >n</code
    > is <em
    >completely</em
    > unrestricted. There is nothing to require <code
    >n</code
    > to be a natural number type, rather than <code
    >Bool</code
    >, <code
    >String</code
    >, <code
    >String &#8594; Bool</code
    >, etc.</p
  ><p
  >In contrast to this difficulty with <code
    >pure</code
    >, consider what if <code
    >n &#8801; String</code
    > in the type of <code
    >fmap</code
    >:</p
  ><pre class="sourceCode haskell"
  ><code
    ><span class="fu"
      >fmap</span
      > <span class="dv"
      >&#8759;</span
      > (a &#8594; b) &#8594; <span class="dt"
      >Vec</span
      > n a &#8594; <span class="dt"
      >Vec</span
      > n b<br
       /></code
    ></pre
  ><p
  >The definition of <code
    >Vec</code
    > guarantees that that there are no values of type <code
    >Vec String a</code
    >. So it's vacuously easy to cover that case (with an empty function). Similarly for <code
    >(&#8859;)</code
    >.</p
  ><p
  >If we were to somehow define <code
    >pure</code
    > with the type given above, then <code
    >pure ()</code
    > would have type <code
    >Vec String ()</code
    > (among many other types). However, there are no values of that type. Hence, <code
    >pure</code
    > cannot be defined without restricting <code
    >n</code
    >.</p
  ><p
  >Since the essential difficulty here is the unrestricted nature of <code
    >n</code
    >, let's look at restricting it. We'll want to include exactly the types that can arise in constructing <code
    >Vec</code
    > values, namely <code
    >Z</code
    >, <code
    >S Z</code
    >, <code
    >S (S Z)</code
    >, <code
    >S (S (S Z))</code
    >, etc.</p
  ><p
  >As a first try, define a class with two instances:</p
  ><pre class="sourceCode haskell"
  ><code
    ><span class="kw"
      >class</span
      > <span class="dt"
      >IsNat</span
      > n<br
       /><br
       /><span class="kw"
      >instance</span
      > <span class="dt"
      >IsNat</span
      > <span class="dt"
      >Z</span
      ><br
       /><span class="kw"
      >instance</span
      > <span class="dt"
      >IsNat</span
      > n &#8658; <span class="dt"
      >IsNat</span
      > (<span class="dt"
      >S</span
      > n)<br
       /></code
    ></pre
  ><p
  >Then change the <code
    >Applicative</code
    > instance to require <code
    >IsNat n</code
    >:</p
  ><pre class="sourceCode haskell"
  ><code
    ><span class="kw"
      >instance</span
      > <span class="dt"
      >IsNat</span
      > n &#8658; <span class="dt"
      >Applicative</span
      > (<span class="dt"
      >Vec</span
      > n) <span class="kw"
      >where</span
      ><br
       />  &#8943;<br
       /></code
    ></pre
  ><p
  >The definition of <code
    >(&#8859;)</code
    > given above still type-checks. Well, not quite. Really, the recursive call to <code
    >(&#8859;)</code
    > fails to type-check, because the <code
    >IsNat</code
    > constraint cannot be proved. One solution is to add that constraint to the vector type:</p
  ><pre class="sourceCode haskell"
  ><code
    ><span class="kw"
      >data</span
      > <span class="dt"
      >Vec</span
      > <span class="dv"
      >&#8759;</span
      > <span class="fu"
      >*</span
      > &#8594; <span class="fu"
      >*</span
      > &#8594; <span class="fu"
      >*</span
      > <span class="kw"
      >where</span
      ><br
       />  <span class="dt"
      >ZVec</span
      > <span class="dv"
      >&#8759;</span
      > <span class="dt"
      >Vec</span
      > <span class="dt"
      >Z</span
      > a<br
       />  (<span class="fu"
      >:&lt;</span
      >) <span class="dv"
      >&#8759;</span
      > <span class="dt"
      >IsNat</span
      > n &#8658; a &#8594; <span class="dt"
      >Vec</span
      > n a &#8594; <span class="dt"
      >Vec</span
      > (<span class="dt"
      >S</span
      > n) a<br
       /></code
    ></pre
  ><p
  >Another is to break the definition <code
    >(&#8859;)</code
    > out into a separate recursion that omits the <code
    >IsNat</code
    > constraint:</p
  ><pre class="sourceCode haskell"
  ><code
    ><span class="kw"
      >instance</span
      > <span class="dt"
      >IsNat</span
      > n &#8658; <span class="dt"
      >Applicative</span
      > (<span class="dt"
      >Vec</span
      > n) <span class="kw"
      >where</span
      ><br
       />  pure <span class="fu"
      >=</span
      > <span class="fu"
      >???</span
      ><br
       />  (&#8859;)  <span class="fu"
      >=</span
      > applyV<br
       /><br
       />applyV <span class="dv"
      >&#8759;</span
      > <span class="dt"
      >Vec</span
      > n (a &#8594; b) &#8594; <span class="dt"
      >Vec</span
      > n a &#8594; <span class="dt"
      >Vec</span
      > n b<br
       /><span class="dt"
      >ZVec</span
      >      <span class="ot"
      >`applyV`</span
      > <span class="dt"
      >ZVec</span
      >      <span class="fu"
      >=</span
      > <span class="dt"
      >ZVec</span
      ><br
       />(f <span class="fu"
      >:&lt;</span
      > fs) <span class="ot"
      >`applyV`</span
      > (x <span class="fu"
      >:&lt;</span
      > xs) <span class="fu"
      >=</span
      > f x <span class="fu"
      >:&lt;</span
      > (fs <span class="ot"
      >`applyV`</span
      > xs)<br
       /></code
    ></pre
  ><p
  >Now, how can we define <code
    >pure</code
    >? We still don't have enough structure. To get that structure, add a method to <code
    >IsNat</code
    >. That method could simply be the definition of <code
    >pure</code
    > that we need.</p
  ><pre class="sourceCode haskell"
  ><code
    ><span class="kw"
      >class</span
      > <span class="dt"
      >IsNat</span
      > n <span class="kw"
      >where</span
      > pureN <span class="dv"
      >&#8759;</span
      > a &#8594; <span class="dt"
      >Vec</span
      > n a<br
       /><br
       /><span class="kw"
      >instance</span
      > <span class="dt"
      >IsNat</span
      > <span class="dt"
      >Z</span
      >                <span class="kw"
      >where</span
      > pureN a <span class="fu"
      >=</span
      > <span class="dt"
      >ZVec</span
      ><br
       /><span class="kw"
      >instance</span
      > <span class="dt"
      >IsNat</span
      > n &#8658; <span class="dt"
      >IsNat</span
      > (<span class="dt"
      >S</span
      > n) <span class="kw"
      >where</span
      > pureN a <span class="fu"
      >=</span
      > a <span class="fu"
      >:&lt;</span
      > pureN a<br
       /></code
    ></pre
  ><p
  >To get this second instance to type-check, we'll have to add the constraint <code
    >IsNat n</code
    > to the <code
    >(:&lt;)</code
    > constructor in <code
    >Vec</code
    >. Then define <code
    >pure = pureN</code
    > for <code
    >Vec</code
    >.</p
  ><p
  >I prefer a variation on this solution. Instead of <code
    >pureN</code
    >, use a method that can only make vectors of <code
    >()</code
    >:</p
  ><pre class="sourceCode haskell"
  ><code
    ><span class="kw"
      >class</span
      > <span class="dt"
      >IsNat</span
      > n <span class="kw"
      >where</span
      > units <span class="dv"
      >&#8759;</span
      > <span class="dt"
      >Vec</span
      > n ()<br
       /><br
       /><span class="kw"
      >instance</span
      >            <span class="dt"
      >IsNat</span
      > <span class="dt"
      >Z</span
      >     <span class="kw"
      >where</span
      > units <span class="fu"
      >=</span
      > <span class="dt"
      >ZVec</span
      ><br
       /><span class="kw"
      >instance</span
      > <span class="dt"
      >IsNat</span
      > n &#8658; <span class="dt"
      >IsNat</span
      > (<span class="dt"
      >S</span
      > n) <span class="kw"
      >where</span
      > units <span class="fu"
      >=</span
      > () <span class="fu"
      >:&lt;</span
      > units<br
       /></code
    ></pre
  ><p
  >Then define</p
  ><pre class="sourceCode haskell"
  ><code
    >  pure a <span class="fu"
      >=</span
      > <span class="fu"
      >fmap</span
      > (<span class="fu"
      >const</span
      > a) units<br
       /></code
    ></pre
  ><p
  >Neat trick, huh? I got it from <a href="http://www.soi.city.ac.uk/~ross/papers/Applicative.html" title="Paper by Conor McBride and Ross Paterson"
    ><em
      >Applicative Programming with Effects</em
      ></a
    > (section 7).</p
  ></div
>

<div id="value-typed-natural-numbers"
><h3
  >Value-typed natural numbers</h3
  ><p
  >There's still another way to define <code
    >IsNat</code
    >, and it's the one I actually use.</p
  ><p
  >Define a type of natural number with matching value &amp; type:</p
  ><pre class="sourceCode haskell"
  ><code
    ><span class="kw"
      >data</span
      > <span class="dt"
      >Nat</span
      > <span class="dv"
      >&#8759;</span
      > <span class="fu"
      >*</span
      > &#8594; <span class="fu"
      >*</span
      > <span class="kw"
      >where</span
      ><br
       />  <span class="dt"
      >Zero</span
      > <span class="dv"
      >&#8759;</span
      >                    <span class="dt"
      >Nat</span
      > <span class="dt"
      >Z</span
      ><br
       />  <span class="dt"
      >Succ</span
      > <span class="dv"
      >&#8759;</span
      > <span class="dt"
      >IsNat</span
      > n &#8658; <span class="dt"
      >Nat</span
      > n &#8594; <span class="dt"
      >Nat</span
      > (<span class="dt"
      >S</span
      > n)<br
       /></code
    ></pre
  ><p
  >Interpret a <code
    >Nat</code
    > as an <code
    >Integer</code
    ></p
  ><pre class="sourceCode haskell"
  ><code
    >natToZ <span class="dv"
      >&#8759;</span
      > <span class="dt"
      >Nat</span
      > n &#8594; <span class="dt"
      >Integer</span
      ><br
       />natToZ <span class="dt"
      >Zero</span
      >     <span class="fu"
      >=</span
      > <span class="dv"
      >0</span
      ><br
       />natToZ (<span class="dt"
      >Succ</span
      > n) <span class="fu"
      >=</span
      > (<span class="fu"
      >succ</span
      > &#8728; natToZ) n<br
       /></code
    ></pre
  ><p
  >I wrote the second clause strangely to emphasize the following lovely property, which corresponds to a simple commutative diagram:</p
  ><pre class="sourceCode haskell"
  ><code
    >natToZ &#8728; <span class="dt"
      >Succ</span
      > <span class="fu"
      >=</span
      > <span class="fu"
      >succ</span
      > &#8728; natToZ<br
       /></code
    ></pre
  ><p
  >This <code
    >natToZ</code
    > function is handy for showing natural numbers:</p
  ><pre class="sourceCode haskell"
  ><code
    ><span class="kw"
      >instance</span
      > <span class="kw"
      >Show</span
      > (<span class="dt"
      >Nat</span
      > n) <span class="kw"
      >where</span
      > <span class="fu"
      >show</span
      > <span class="fu"
      >=</span
      > <span class="fu"
      >show</span
      > &#8728; natToZ<br
       /></code
    ></pre
  ><p
  >A fun &amp; strange thing about <code
    >Nat n</code
    > is that it can have at most one inhabitant for any type <code
    >n</code
    >. We can synthesize that inhabitant via an alternative definition of the <code
    >IsNat</code
    > class defined (twice) above:</p
  ><pre class="sourceCode haskell"
  ><code
    ><span class="kw"
      >class</span
      > <span class="dt"
      >IsNat</span
      > n <span class="kw"
      >where</span
      > nat <span class="dv"
      >&#8759;</span
      > <span class="dt"
      >Nat</span
      > n<br
       /><br
       /><span class="kw"
      >instance</span
      >            <span class="dt"
      >IsNat</span
      > <span class="dt"
      >Z</span
      >     <span class="kw"
      >where</span
      > nat <span class="fu"
      >=</span
      > <span class="dt"
      >Zero</span
      ><br
       /><span class="kw"
      >instance</span
      > <span class="dt"
      >IsNat</span
      > n &#8658; <span class="dt"
      >IsNat</span
      > (<span class="dt"
      >S</span
      > n) <span class="kw"
      >where</span
      > nat <span class="fu"
      >=</span
      > <span class="dt"
      >Succ</span
      > nat<br
       /></code
    ></pre
  ><p
  >Using this latest version of <code
    >IsNat</code
    >, we can easily define <code
    >units</code
    > (and hence <code
    >pure</code
    > on <code
    >Vec n</code
    > for <code
    >IsNat n</code
    >):</p
  ><pre class="sourceCode haskell"
  ><code
    >units <span class="dv"
      >&#8759;</span
      > <span class="dt"
      >IsNat</span
      > n &#8658; <span class="dt"
      >Vec</span
      > n ()<br
       />units <span class="fu"
      >=</span
      > unitsN nat<br
       /><br
       />unitsN <span class="dv"
      >&#8759;</span
      > <span class="dt"
      >Nat</span
      > n &#8594; <span class="dt"
      >Vec</span
      > n ()<br
       />unitsN <span class="dt"
      >Zero</span
      >     <span class="fu"
      >=</span
      > <span class="dt"
      >ZVec</span
      ><br
       />unitsN (<span class="dt"
      >Succ</span
      > n) <span class="fu"
      >=</span
      > () <span class="fu"
      >:&lt;</span
      > unitsN n<br
       /></code
    ></pre
  ><p
  >I prefer this latest <code
    >IsNat</code
    > definition over the previous two, because it relies only on <code
    >Nat</code
    >, which is simpler and more broadly useful than <code
    >Vec</code
    >. Examples abound, including improving an recent post, as we'll see now.</p
  ></div
>

<div id="revisiting-type-bounded-numbers"
><h3
  >Revisiting type-bounded numbers</h3
  ><p
  >The post <a href="http://conal.net/blog/posts/type-bounded-numbers/" title="blog post"
    ><em
      >Type-bounded numbers</em
      ></a
    > defined a type <code
    >BNat n</code
    > of natural numbers less than <code
    >n</code
    >, which can be used, for instance, as numerical digits in base <code
    >n</code
    >.</p
  ><pre class="sourceCode haskell"
  ><code
    ><span class="kw"
      >data</span
      > <span class="dt"
      >BNat</span
      > <span class="dv"
      >&#8759;</span
      > <span class="fu"
      >*</span
      > &#8594; <span class="fu"
      >*</span
      > <span class="kw"
      >where</span
      ><br
       />  <span class="dt"
      >BZero</span
      > <span class="dv"
      >&#8759;</span
      >          <span class="dt"
      >BNat</span
      > (<span class="dt"
      >S</span
      > n)<br
       />  <span class="dt"
      >BSucc</span
      > <span class="dv"
      >&#8759;</span
      > <span class="dt"
      >BNat</span
      > n &#8594; <span class="dt"
      >BNat</span
      > (<span class="dt"
      >S</span
      > n)<br
       /></code
    ></pre
  ><p
  >One useful operation is conversion from integer to <code
    >BNat n</code
    >. This operation had the awkward task of coming up with <code
    >BNat</code
    > structure. The solution given was to introduce a type class, with instances for <code
    >Z</code
    > and <code
    >S</code
    >:</p
  ><pre class="sourceCode haskell"
  ><code
    ><span class="kw"
      >class</span
      > <span class="dt"
      >HasBNat</span
      > n <span class="kw"
      >where</span
      > toBNat <span class="dv"
      >&#8759;</span
      > <span class="dt"
      >Integer</span
      > &#8594; <span class="dt"
      >Maybe</span
      > (<span class="dt"
      >BNat</span
      > n)<br
       /><br
       /><span class="kw"
      >instance</span
      > <span class="dt"
      >HasBNat</span
      > <span class="dt"
      >Z</span
      > <span class="kw"
      >where</span
      > toBNat _ <span class="fu"
      >=</span
      > <span class="kw"
      >Nothing</span
      ><br
       /><br
       /><span class="kw"
      >instance</span
      > <span class="dt"
      >HasBNat</span
      > n &#8658; <span class="dt"
      >HasBNat</span
      > (<span class="dt"
      >S</span
      > n) <span class="kw"
      >where</span
      ><br
       />  toBNat m <span class="fu"
      >|</span
      > m <span class="fu"
      >&lt;</span
      > <span class="dv"
      >1</span
      >     <span class="fu"
      >=</span
      > <span class="kw"
      >Just</span
      > <span class="dt"
      >BZero</span
      ><br
       />           <span class="fu"
      >|</span
      > <span class="fu"
      >otherwise</span
      > <span class="fu"
      >=</span
      > <span class="fu"
      >fmap</span
      > <span class="dt"
      >BSucc</span
      > (toBNat (<span class="fu"
      >pred</span
      > m))<br
       /></code
    ></pre
  ><p
  >We can instead eliminate the <code
    >HasBNat</code
    > class and reuse the <code
    >IsNat</code
    > class, as in the last technique above for defining <code
    >units</code
    > or <code
    >pure</code
    >.</p
  ><pre class="sourceCode haskell"
  ><code
    >toBNat <span class="dv"
      >&#8759;</span
      > &#8704; n<span class="fu"
      >.</span
      > <span class="dt"
      >IsNat</span
      > n &#8658; <span class="dt"
      >Integer</span
      > &#8594; <span class="dt"
      >Maybe</span
      > (<span class="dt"
      >BNat</span
      > n)<br
       />toBNat <span class="fu"
      >=</span
      > loop n <span class="kw"
      >where</span
      ><br
       />  n <span class="fu"
      >=</span
      > nat <span class="dv"
      >&#8759;</span
      > <span class="dt"
      >Nat</span
      > n<br
       />  loop <span class="dv"
      >&#8759;</span
      > <span class="dt"
      >Nat</span
      > n' &#8594; <span class="dt"
      >Integer</span
      > &#8594; <span class="dt"
      >Maybe</span
      > (<span class="dt"
      >BNat</span
      > n')<br
       />  loop <span class="dt"
      >Zero</span
      >      _ <span class="fu"
      >=</span
      > <span class="kw"
      >Nothing</span
      ><br
       />  loop (<span class="dt"
      >Succ</span
      > _)  <span class="dv"
      >0</span
      > <span class="fu"
      >=</span
      > <span class="kw"
      >Just</span
      > <span class="dt"
      >BZero</span
      ><br
       />  loop (<span class="dt"
      >Succ</span
      > n') m <span class="fu"
      >=</span
      > <span class="fu"
      >fmap</span
      > <span class="dt"
      >BSucc</span
      > (loop n' (<span class="fu"
      >pred</span
      > m))<br
       /></code
    ></pre
  ></div
>

<div id="a-monad-instance"
><h3
  >A Monad instance</h3
  ><p
  >First the easy parts: standard definitions in terms of <code
    >pure</code
    > and <code
    >join</code
    >:</p
  ><pre class="sourceCode haskell"
  ><code
    ><span class="kw"
      >instance</span
      > <span class="dt"
      >IsNat</span
      > n &#8658; <span class="kw"
      >Monad</span
      > (<span class="dt"
      >Vec</span
      > n) <span class="kw"
      >where</span
      ><br
       />  <span class="fu"
      >return</span
      >  <span class="fu"
      >=</span
      > pure<br
       />  v <span class="fu"
      >&gt;&gt;=</span
      > f <span class="fu"
      >=</span
      > join (<span class="fu"
      >fmap</span
      > f v)<br
       /></code
    ></pre
  ><p
  >The <code
    >join</code
    > function on <code
    >Vec n</code
    > is just like <code
    >join</code
    > for functions and for streams. (Rightly so, considering the principle of <a href="http://conal.net/blog/tag/type-class-morphism/" title="Posts on type class morphisms"
    >type class morphism</a
    >s.) It uses diagonalization, and one way to think of vector <code
    >join</code
    > is that it extracts the diagonal of a square matrix.</p
  ><pre class="sourceCode haskell"
  ><code
    >join <span class="dv"
      >&#8759;</span
      > <span class="dt"
      >Vec</span
      > n (<span class="dt"
      >Vec</span
      > n a) &#8594; <span class="dt"
      >Vec</span
      > n a<br
       />join <span class="dt"
      >ZVec</span
      >      <span class="fu"
      >=</span
      > <span class="dt"
      >ZVec</span
      ><br
       />join (v <span class="fu"
      >:&lt;</span
      > vs) <span class="fu"
      >=</span
      > headV v <span class="fu"
      >:&lt;</span
      > join (<span class="fu"
      >fmap</span
      > tailV vs)<br
       /></code
    ></pre
  ><p
  >The <code
    >headV</code
    > and <code
    >tailV</code
    > functions are like <code
    >head</code
    > and <code
    >tail</code
    > but understand lengths:</p
  ><pre class="sourceCode haskell"
  ><code
    >headV <span class="dv"
      >&#8759;</span
      > <span class="dt"
      >Vec</span
      > (<span class="dt"
      >S</span
      > n) a &#8594; a<br
       />headV (a <span class="fu"
      >:&lt;</span
      > _) <span class="fu"
      >=</span
      > a<br
       /></code
    ></pre
  ><pre class="sourceCode haskell"
  ><code
    >tailV <span class="dv"
      >&#8759;</span
      > <span class="dt"
      >Vec</span
      > (<span class="dt"
      >S</span
      > n) a &#8594; <span class="dt"
      >Vec</span
      > n a<br
       />tailV (_ <span class="fu"
      >:&lt;</span
      > as) <span class="fu"
      >=</span
      > as<br
       /></code
    ></pre
  ><p
  >Unlike their list counterparts, <code
    >headV</code
    > and <code
    >tailV</code
    > are <em
    >safe</em
    >, in that the precondition of non-emptiness is verified statically.</p
  ></div
>
<p><a href="http://conal.net/blog/?flattrss_redirect&amp;id=293&amp;md5=0fd4950067e60840fabf4f89a33ab982"><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/doing-more-with-length-typed-vectors/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%2Fdoing-more-with-length-typed-vectors&amp;language=en_GB&amp;category=text&amp;title=Doing+more+with+length-typed+vectors&amp;description=The+post+Fixing+lists+defined+a+%28commonly+used%29+type+of+vectors%2C+whose+lengths+are+determined+statically%2C+by+type.+In+Vec+n+a%2C+the+length+is+n%2C+and+the+elements+have...&amp;tags=applicative+functor%2Cmonad%2Cnumber%2Cvector%2Cblog" type="text/html" />
	</item>
		<item>
		<title>The C language is purely functional</title>
		<link>http://conal.net/blog/posts/the-c-language-is-purely-functional</link>
		<comments>http://conal.net/blog/posts/the-c-language-is-purely-functional#comments</comments>
		<pubDate>Wed, 20 May 2009 01:19:21 +0000</pubDate>
		<dc:creator><![CDATA[Conal]]></dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[history]]></category>
		<category><![CDATA[monad]]></category>
		<category><![CDATA[philosophy]]></category>

		<guid isPermaLink="false">http://conal.net/blog/?p=87</guid>
		<description><![CDATA[There has been a scurry of reaction on twitter and reddit to Robert Fischer&#8217;s post saying that Scala is Not a Functional Programming Language. James Iry responded by saying that analogous reasoning leads to the conclusion that Erlang is Not Functional My first inclination was to suggest that Haskell, as commonly practiced (with monadic IO), [&#8230;]]]></description>
				<content:encoded><![CDATA[<!-- 

Title: The C language is purely functional

Tags: philosophy, monad, history

URL: http://conal.net/blog/posts/the-c-language-is-purely-functional/

-->

<!-- references -->

<!-- teaser -->

<p>There has been a scurry of reaction on twitter and reddit to Robert Fischer&#8217;s post saying that <a href="http://www.reddit.com/goto?id=8kl8l">Scala is Not a Functional Programming Language</a>.
James Iry responded by saying that analogous reasoning leads to the conclusion that <a href="http://www.reddit.com/goto?id=8krbo">Erlang is Not Functional</a></p>

<p>My first inclination was to suggest that Haskell, as commonly practiced (with monadic IO), is not a functional language either.
Instead, I&#8217;m going to explain how it is that <em>the C language is purely functional</em>.</p>

<!--
**Edits**:

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

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

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

<h3>The story of C</h3>

<p>First, let me make that claim more precise.
What I really mean is that almost everyone who &#8220;writes C programs&#8221; is really programming in a purely functional language.
Modulo some minor historical accidents.</p>

<p>&#8220;C programmers&#8221; really program not in C, but in the purely functional language <em>cpp</em> (<a href="http://en.wikipedia.org/wiki/C_preprocessor">the &#8220;C Preprocessor&#8221;</a>).
As with any purely functional language, cpp consists only of (nestable) <em>expressions</em>, not statements.
Now here&#8217;s the clever part: when <em>evaluated</em> (not executed), a cpp expression yields a (pure) value of type <code>C</code>, which is an ADT (abstract data type) that represents imperative programs.
That value of type <code>C</code> is then <em>executed</em> (not evaluated) by the cpp language&#8217;s RTS (run-time system).
As a clever optimization, cpp&#8217;s RTS actually includes a code generator, considerably improving performance over more naïve implementations of the <code>C</code> abstract data type.</p>

<p>(So now you can see that, &#8220;C programmer&#8221; is almost always a misnomer when applied to a person.
Instead people are cpp programmers, and cpp programs are the real C programmers (producers of <code>C</code>).
I don&#8217;t think I can buck this misnomer, so I&#8217;ll stay with the herd and use &#8220;C programming&#8221; to mean cpp programming.)</p>

<p>In this way, the geniuses Brian Kernighan and Dennis Ritchie applied monads (from category theory) to programming language design considerably before the work of Moggi and Wadler.
(Even earlier examples of this idea can be found, so I&#8217;m taking liberty with history, choosing to give K&amp;R credit for the sake of this post.)</p>

<p>Now along the way, some mistakes were made that tarnished the theoretical beauty of cpp+C:</p>

<ul>
<li><p>Although cpp is in spirit purely functional, pragmatists insisted on the unnecessary and theoretically awkward construct <code>#undef</code>, which allows a single name to be re-defined.</p></li>
<li><p>Scoping rules are not as clean as, say, the lambda calculus or Scheme,  (But hey &#8212; even John McCarthy got scoping wrong.)</p></li>
<li><p>The <code>C</code> ADT is implemented simply as <code>String</code> (or <code>char *</code>, for you type theorists, using a notation from Kleene), and the representation is <em>exposed</em> rather than hidden, so that cpp programs operate directly on strings.  The wisdom of data abstraction caught on later.</p></li>
</ul>

<p>Fortunately for purists, the relatively obscure programming language <a href="http://haskell.org">Haskell</a> restored the original untarnished beauty of K&amp;R&#8217;s vision by fixing these defects.
The type system was modernized, scoping rules improved, and the <code>C</code> type (renamed to &#8220;<code>IO</code>&#8220;, to avoid expensive legal battles) made abstract.</p>

<p>(Admittedly, Haskell also had some shameful pre-teen influences from hooligans like Church, Curry, Landin, and Milner, before it settled into its true cpp+C nature, under the guiding influence of Wadler (under the influence of Moggi).)</p>

<h3>What about Haskell?</h3>

<p>Which leads to the question: is Haskell+IO a purely functional programming language?</p>

<p>Sure it is, even as much as its predecessor C (more precisely, cpp+C).</p>

<p>Some who ought to know better would claim that Haskell+IO is only <em>technically</em> pure.
(See <a href="http://www.reddit.com/r/programming/comments/8krbo/erlang_is_not_functional_response_to_scala_is_not/c09lqfi">claims and follow-up discussion</a>, in response to a remark from James Iry.)</p>

<p>I must then respond that, in that case, <em>even C programming</em> is only technically pure.</p>

<p>Which is absurd.</p>
<p><a href="http://conal.net/blog/?flattrss_redirect&amp;id=87&amp;md5=a592089bcedaab4dfa655e3347d0dcc0"><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/the-c-language-is-purely-functional/feed</wfw:commentRss>
		<slash:comments>43</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%2Fthe-c-language-is-purely-functional&amp;language=en_GB&amp;category=text&amp;title=The+C+language+is+purely+functional&amp;description=There+has+been+a+scurry+of+reaction+on+twitter+and+reddit+to+Robert+Fischer%26%238217%3Bs+post+saying+that+Scala+is+Not+a+Functional+Programming+Language.+James+Iry+responded+by+saying+that...&amp;tags=history%2Cmonad%2Cphilosophy%2Cblog" type="text/html" />
	</item>
		<item>
		<title>Denotational design with type class morphisms</title>
		<link>http://conal.net/blog/posts/denotational-design-with-type-class-morphisms</link>
		<comments>http://conal.net/blog/posts/denotational-design-with-type-class-morphisms#comments</comments>
		<pubDate>Thu, 19 Feb 2009 02:34:08 +0000</pubDate>
		<dc:creator><![CDATA[Conal]]></dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[applicative functor]]></category>
		<category><![CDATA[arrow]]></category>
		<category><![CDATA[associated type]]></category>
		<category><![CDATA[functor]]></category>
		<category><![CDATA[monad]]></category>
		<category><![CDATA[monoid]]></category>
		<category><![CDATA[paper]]></category>
		<category><![CDATA[semantics]]></category>
		<category><![CDATA[trie]]></category>
		<category><![CDATA[type class morphism]]></category>

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

Title: Denotational design with type class morphisms

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

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

-->

<!-- references -->

<!-- teaser -->

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

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

<p>The abstract:</p>

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

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

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

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

<!--
**Edits**:

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

		<guid isPermaLink="false">http://conal.net/blog/posts/a-handy-generalized-filter/</guid>
		<description><![CDATA[For quite a while, I&#8217;ve been using a handy operation for filtering functional events: justE :: Event (Maybe a) -&#62; Event a The idea of justE is to drop the Nothing-valued occurrences and strip off the Just constructors from the remaining occurrences. Recently I finally noticed the similarity with a standard function (in Data.Maybe): catMaybes [&#8230;]]]></description>
				<content:encoded><![CDATA[<!-- 

Title: A handy generalized filter

Tags: joinMaybes, monads, events, filter

-->

<!-- references -->

<!-- teaser -->

<p>For quite a while, I&#8217;ve been using a handy operation for filtering functional events:</p>

<pre><code>justE :: Event (Maybe a) -&gt; Event a
</code></pre>

<p>The idea of <code>justE</code> is to drop the <code>Nothing</code>-valued occurrences and strip off the <code>Just</code> constructors from the remaining occurrences.  Recently I finally noticed the similarity with a standard function (in <code>Data.Maybe</code>):</p>

<pre><code>catMaybes :: [Maybe a] -&gt; [a]
</code></pre>

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

<p>I <a href="http://tunes.org/~nef/logs/haskell/07.12.26" title="IRC log: #haskell, December 26 2007">asked on #haskell</a> about a common generalization, and oerjan offered the following:</p>

<pre><code>joinMaybes :: MonadPlus m =&gt; m (Maybe a) -&gt; m a
joinMaybes = (&gt;&gt;= maybe mzero return)
</code></pre>

<p>I like this name and definition very much, including the use of <code>mzero</code> and <code>return</code> for empty and singleton monadic values, respectively.  I particularly like how it works out for lists and events.  Each element is passed into <code>maybe mzero return</code>, so that a <code>Nothing</code> becomes empty (<code>mzero</code>), while a <code>Just x</code> becomes a singleton (<code>return x</code>).</p>

<p>I also like how <code>joinMaybes</code> specializes easily into traditional, predicate-based filtering, generalizing the standard <code>filter</code> function on lists:</p>

<pre><code>filterMP :: MonadPlus m =&gt; (a -&gt; Bool) -&gt; m a -&gt; m a
filterMP p m = joinMaybes (liftM f m)
 where
   f a | p a       = Just a
       | otherwise = Nothing
</code></pre>

<p>So it&#8217;s easy to define <code>filterMP</code> in terms of <code>joinMaybes</code> (and hence <code>filter</code> in terms of <code>catMaybes</code>).  What about the reverse?  Here&#8217;s one go at it:</p>

<pre><code>filterMP' :: MonadPlus m =&gt; (a -&gt; Bool) -&gt; m a -&gt; m a
filterMP' p = (&gt;&gt;= f)
 where
   f a | p a       = return a
       | otherwise = mzero

joinMaybes' :: MonadPlus m =&gt; m (Maybe a) -&gt; m a
joinMaybes' = liftM fromJust . filterMP' isJust
</code></pre>

<p>Comparable simplicity, but I don&#8217;t like the <code>isJust</code> and <code>fromJust</code>.  Not only is there some redundant checking, but the <code>fromJust</code> function is partial, and so this definition is not so obviously total to an automated checker like <a href="http://www-users.cs.york.ac.uk/~ndm/catch/" title="Project page: &quot;Catch: Case Totality Checker for Haskell&quot;">Catch</a>.</p>

<hr />

<p><em>Edit 2008-02-08</em>: added a &#8220;Continue reading &#8230;&#8221; token, to keep my blog&#8217;s front page uncluttered.</p>
<p><a href="http://conal.net/blog/?flattrss_redirect&amp;id=12&amp;md5=380e46a02c42296b7d57cd6b5619b167"><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-handy-generalized-filter/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-handy-generalized-filter&amp;language=en_GB&amp;category=text&amp;title=A+handy+generalized+filter&amp;description=For+quite+a+while%2C+I%26%238217%3Bve+been+using+a+handy+operation+for+filtering+functional+events%3A+justE+%3A%3A+Event+%28Maybe+a%29+-%26gt%3B+Event+a+The+idea+of+justE+is+to+drop+the...&amp;tags=events%2Cfilter%2CjoinMaybes%2Cmonad%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>
	</channel>
</rss>
