<?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; future value</title>
	<atom:link href="http://conal.net/blog/tag/future-value/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>Another angle on functional future values</title>
		<link>http://conal.net/blog/posts/another-angle-on-functional-future-values</link>
		<comments>http://conal.net/blog/posts/another-angle-on-functional-future-values#comments</comments>
		<pubDate>Mon, 05 Jan 2009 04:01:05 +0000</pubDate>
		<dc:creator><![CDATA[Conal]]></dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[caching]]></category>
		<category><![CDATA[FRP]]></category>
		<category><![CDATA[functional reactive programming]]></category>
		<category><![CDATA[future value]]></category>
		<category><![CDATA[referential transparency]]></category>
		<category><![CDATA[type class morphism]]></category>
		<category><![CDATA[type composition]]></category>

		<guid isPermaLink="false">http://conal.net/blog/?p=73</guid>
		<description><![CDATA[An earlier post introduced functional future values, which are values that cannot be known until the future, but can be manipulated in the present. That post presented a simple denotational semantics of future values as time/value pairs. With a little care in the definition of Time (using the Max monoid), the instances of Functor, Applicative, [&#8230;]]]></description>
				<content:encoded><![CDATA[<!-- 

Title: Another angle on functional future values

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

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

-->

<!-- references -->

<!-- teaser -->

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

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

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

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

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

<p>I started playing with future values and unambiguous choice as a way to implement <a href="http://haskell.org/haskellwiki/Reactive" title="Wiki page for the Reactive library">Reactive</a>, a library for functional reactive programming (FRP).
(See <em><a href="http://conal.net/blog/posts/reactive-values-from-the-future/" title="blog post">Reactive values from the future</a></em> and <em><a href="http://conal.net/papers/push-pull-frp/" title="Paper">Push-pull functional reactive programming</a></em>.)
Over the last few days, I&#8217;ve given some thought to ways to implement future values without unambiguous choice.
This post describes one such alternative.</p>

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

<ul>
<li>2010-08-25: Replaced references to <em><a href="http://conal.net/papers/simply-reactive" title="Paper: &quot;Simply efficient functional reactivity (superceded)&quot;">Simply efficient functional reactivity</a></em> with <em><a href="http://conal.net/papers/push-pull-frp/" title="Paper">Push-pull functional reactive programming</a></em>.
The latter paper supercedes the former.</li>
<li>2010-08-25: Fixed the <code>unFuture</code> field of FutureG to be <code>TryFuture</code>.</li>
</ul>

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

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

<h3>Futures, presently</h3>

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

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

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

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

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

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

<pre><code>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>This <code>mappend</code> definition could be written more simply:</p>

<pre><code>  u@(Future (t,_)) `mappend` u'@(Future (t',_)) =
    if t &lt;= t' then u else u'
</code></pre>

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

<h3>Futures as functions</h3>

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

<pre><code>until :: BehaviorG t a -&gt; FutureG t (BehaviorG t a) -&gt; BehaviorG t a
</code></pre>

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

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

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

<pre><code>(b `until` Future (t',b')) `at` t = b'' `at` t
 where
   b'' = if t &lt;= t' then b else b'
</code></pre>

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

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

<pre><code>type TryFuture t a = Time t -&gt; Maybe (S.FutureG t a)

tryFuture :: F.FutureG t a -&gt; TryFuture t a
</code></pre>

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

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

<pre><code>type F.FutureG = TryFuture  -- first try
</code></pre>

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

<pre><code>newtype FutureG t a = Future { unFuture :: TryFuture t a } -- second try
</code></pre>

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

<pre><code>future :: TryFuture t a -&gt; FutureG t a
future = Future

tryFuture :: FutureG t a -&gt; TryFuture t a
tryFuture = unFuture
</code></pre>

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

<pre><code>inFuture  :: (TryFuture t a -&gt; TryFuture t' a')
          -&gt; (FutureG   t a -&gt; FutureG   t' a')

inFuture2 :: (TryFuture t a -&gt; TryFuture t' a' -&gt; TryFuture t'' a'')
          -&gt; (FutureG   t a -&gt; FutureG   t' a' -&gt; FutureG   t'' a'')
</code></pre>

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

<pre><code>inFuture  = unFuture ~&gt; Future

inFuture2 = unFuture ~&gt; inFuture 

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

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

<pre><code>instance Functor (FutureG t) where
  fmap = inFuture.fmap.fmap.fmap

instance (Bounded t, Ord t) =&gt; Applicative (FutureG t) where
  pure  = Future . pure.pure.pure
  (&lt;*&gt;) = (inFuture2.liftA2.liftA2) (&lt;*&gt;)
</code></pre>

<h4>Type composition</h4>

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

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

<pre><code>type FutureG t = (-&gt;) (Time t) :. Maybe :. S.FutureG t  -- actual definition
</code></pre>

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

<h4>Monoid</h4>

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

<pre><code>instance Monoid (g (f a)) =&gt; Monoid ((g :. f) a) where
  { mempty = O mempty; mappend = inO2 mappend }
</code></pre>

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

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

<pre><code>-- standard Monoid instance for Applicative applied to Monoid
instance (Applicative (g :. f), Monoid a) =&gt; Monoid ((g :. f) a) where
  { mempty = pure mempty; mappend = liftA2 mappend }
</code></pre>

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

<pre><code>instance (Ord t, Bounded t) =&gt; Monoid (FutureG t a) where
  mempty  = (  O .  O ) mempty   -- or future mempty
  mappend = (inO2.inO2) mappend
</code></pre>

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

<pre><code>mempty

  == {- definition -} 

O (O mempty)

  == {- mempty on functions -}

O (O (const mempty))

  == {- mempty on Maybe -}

O (O (const Nothing))
</code></pre>

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

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

<pre><code>O (O f) `mappend` O (O f')

  == {- mappend on FutureG -}

O (O (f `mappend` f'))

  == {- mappend on functions -}

O (O ( t -&gt; f t `mappend` f' t))

  == {- mappend on Maybe -}

O (O ( t -&gt; f t `mappendMb` f' t))
  where
    Nothing `mappendMb` mb'    = mb'
    mb `mappendMb` Nothing     = mb
    Just u `mappendMb` Just u' = Just (u `mappend` u')
</code></pre>

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

<pre><code>u@(Future (s,_)) `mappend` u'@(Future (s',_)) = if s &lt;= s' then u else u'
</code></pre>

<p>or</p>

<pre><code>u `mappend` u' = if futTime u &lt;= futTime u' then u else u'

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

<p>or just</p>

<pre><code>mappend = minBy futTime
</code></pre>

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

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

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

<pre><code>sToF :: Ord t =&gt; S.FutureG t a -&gt; F.FutureG t a

fToS :: Ord t =&gt; F.FutureG t a -&gt; S.FutureG t a
</code></pre>

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

<pre><code>sToF u@(S.Future (t, _)) =
  future ( t' -&gt; if t' &lt;= t then Nothing else Just u)
</code></pre>

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

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

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

<pre><code>sToF mempty == mempty

sToF (u `mappend` u') == sToF u `mappend` sToF u'
</code></pre>

<h3>Caching futures</h3>

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

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

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

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

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

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

<pre><code>data C.FutureG t a =
  Future (SampleVar t) (IVar (S.FutureG t a)) (F.FutureG t a)
</code></pre>

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

<pre><code>data C.FutureG t a =
  Future (SampleVar t) (MVar (Either (F.FutureG t a) (FF.FutureG t a)))
</code></pre>

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

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

<pre><code>dToF :: Ord     t =&gt; C.FutureG t a -&gt; F.FutureG t a

fToD :: Bounded t =&gt; F.FutureG t a -&gt; C.FutureG t a
</code></pre>

<p>The implementation</p>

<pre><code>dToF (C.Future tv uv uf) =
  F.Future $  t' -&gt; unsafePerformIO $
    do mb &lt;- tryReadIVar uv
       case mb of
         j@(Just (S.Future (Max t,_))) -&gt;
           return (if t' &lt;= t then Nothing else j)
         Nothing        -&gt;
           do tlo &lt;- readSampleVar tv
              if t' &lt;= tlo then
                 return Nothing
               else
                 do let mb' = F.unFuture uf t'
                    writeIVarMaybe uv mb'
                    return mb'

-- Perhaps write to an IVar
writeIVarMaybe :: IVar a -&gt; Maybe a -&gt; IO ()
writeIVarMaybe v = maybe (return ()) (writeIVar v)

fToD uf = unsafePerformIO $
          do tv &lt;- newSampleVar t0
             uv &lt;- newIVar
             writeIVarMaybe uv (F.unFuture uf t0)
             return (Future tv uv uf)
 where
   t0 = minBound
</code></pre>

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

<pre><code>inF :: (Ord t, Bounded t') =&gt;
       (F.FutureG t a -&gt; F.FutureG t' a')
    -&gt; (  FutureG t a -&gt;   FutureG t' a')
inF = dToF ~&gt; fToD

inF2 :: (Ord t, Bounded t', Ord t', Bounded t'') =&gt;
        (F.FutureG t a -&gt; F.FutureG t' a' -&gt; F.FutureG t'' a'')
     -&gt; (  FutureG t a -&gt;   FutureG t' a' -&gt;   FutureG t'' a'')
inF2 = dToF ~&gt; inF
</code></pre>

<p>Then</p>

<pre><code>instance (Ord t, Bounded t) =&gt; Monoid (FutureG t a) where
  mempty  = fToD mempty
  mappend = inF2 mappend

instance (Ord t, Bounded t) =&gt; Functor     (FutureG t) where
  fmap = inF . fmap

instance (Ord t, Bounded t) =&gt; Applicative (FutureG t) where
  pure  = fToD . pure
  (&lt;*&gt;) = inF2 (&lt;*&gt;)
</code></pre>

<h3>Wrap-up</h3>

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

<p>What interests me most above is the use of <code>unsafePerformIO</code> here while preserving referential transparency, thanks to the invariant on <code>F.FutureG</code> (and the consequent monotonicity property).
The heart of lazy evaluation of <em>pure</em> functional programs is just such an update, replacing a thunk with its weak head normal form (whnf).
What general principles can we construct that allow us to use efficient, destructive updating and still have referential transparency?
The important thing above seems to be the careful definition of an abstract interface such that the effect of state updates is semantically invisible through the interface.</p>
<p><a href="http://conal.net/blog/?flattrss_redirect&amp;id=73&amp;md5=7a9fda2441e621e5220ead93a09bb210"><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/another-angle-on-functional-future-values/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%2Fanother-angle-on-functional-future-values&amp;language=en_GB&amp;category=text&amp;title=Another+angle+on+functional+future+values&amp;description=An+earlier+post+introduced+functional+future+values%2C+which+are+values+that+cannot+be+known+until+the+future%2C+but+can+be+manipulated+in+the+present.+That+post+presented+a+simple+denotational...&amp;tags=caching%2CFRP%2Cfunctional+reactive+programming%2Cfuture+value%2Creferential+transparency%2Ctype+class+morphism%2Ctype+composition%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>Reactive normal form</title>
		<link>http://conal.net/blog/posts/reactive-normal-form</link>
		<comments>http://conal.net/blog/posts/reactive-normal-form#comments</comments>
		<pubDate>Fri, 25 Jan 2008 23:00:59 +0000</pubDate>
		<dc:creator><![CDATA[Conal]]></dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[future value]]></category>
		<category><![CDATA[normal form]]></category>
		<category><![CDATA[reactive value]]></category>
		<category><![CDATA[reactivity]]></category>

		<guid isPermaLink="false">http://conal.net/blog/posts/reactive-normal-form/</guid>
		<description><![CDATA[The post &#8220;Reactive values from the future&#8221; presented a simple formulation of functional events and reactive values, built on a functional notion of future values. In the current post, I&#8217;ll describe some of the implementation of events and reactive values*. Reactive values Switching As mentioned previously, the stepper function corresponds directly to the representation of [&#8230;]]]></description>
				<content:encoded><![CDATA[<!--

Title: Reactive normal
tags: reactivity, future values, normal form, reactive values, events

-->

<!-- references -->

<!-- teaser -->

<p>The post <a href="http://conal.net/blog/posts/reactive-values-from-the-future/" title="Blog post: &quot;Reactive values from the future&quot;">&#8220;Reactive values from the future&#8221;</a> presented a simple formulation of functional <em>events</em> and <em>reactive values</em>, built on a functional notion of <em><a href="http://conal.net/blog/posts/future-values/" title="Blog post: &quot;Future values&quot;">future values</a></em>.  In the current post, I&#8217;ll describe some of the implementation of events and reactive values*.</p>

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

<h2>Reactive values</h2>

<h3>Switching</h3>

<p>As mentioned <a href="http://conal.net/blog/posts/reactive-values-from-the-future/" title="Blog post: &quot;Reactive values from the future&quot;">previously</a>, the <code>stepper</code> function corresponds directly to the representation of <code>Reactive</code>.</p>

<pre><code>data Reactive a = Stepper a (Event a)

stepper :: a -&gt; Event a -&gt; Reactive a
stepper = Stepper
</code></pre>

<p>The representation of all other functions must therefore produce their result in terms of <code>stepper</code>, which thereby serves as a kind of <em>reactive normal form</em> (RNF).  The implementation can be understood as a set of rewrite rules that convert arbitrary reactive expressions into RNF.  (These rewrite rules are all provably correct based on a simple semantics of events and reactive values.)</p>

<p>The more general switching form can be expressed in terms of <code>switcher</code> and (monadic) <code>join</code>:</p>

<pre><code>switcher :: Reactive a -&gt; Event (Reactive a) -&gt; Reactive a
r `switcher` er = join (r `stepper` er)
</code></pre>

<p>We&#8217;ll see below how to reduce <code>join</code> to a <code>stepper</code>.</p>

<h3>Functor</h3>

<p>As a simple example, <code>fmap f</code> applies a function <code>f</code> to a reactive value pointwise, which is equivalent to applying <code>f</code> to the initial value and to each occurrence value.</p>

<pre><code>instance Functor Reactive where
  fmap f (a `Stepper` e) = f a `stepper` fmap f e
</code></pre>

<p>The <code>Event</code> functor is also easily defined.  <a href="http://conal.net/blog/posts/reactive-values-from-the-future/" title="Blog post: &quot;Reactive values from the future&quot;">Recall</a> that an event is a future reactive value:</p>

<pre><code>newtype Event = Future (Reactive a)
</code></pre>

<p>We want to map a given function over that reactive value, which we can do by combining <code>fmap</code> on <code>Future</code> with <code>fmap</code> on <code>Reactive</code>.</p>

<pre><code>instance Functor Event where
  fmap f (Event fut) = Event ((fmap.fmap) f fut)
</code></pre>

<h3>Applicative</h3>

<p>The <code>Functor</code> definitions for <code>Reactive</code> and <code>Event</code> are straightforward, because the <code>Stepper</code> structure is easily preserved.  A more challenging case is <code>Applicative</code>.</p>

<pre><code>instance Applicative Reactive where ... 
</code></pre>

<p>First the easy part.  A pure value <code>a</code> becomes reactive by using <code>a</code> as the initial value and <code>mempty</code> as the (never-occuring) change event:</p>

<pre><code>  pure a = a `stepper` mempty
</code></pre>

<p>Consider next applying a reactive function to a reactive argument:</p>

<pre><code>  rf@(f `Stepper` Event futf) &lt;*&gt; rx@(x `Stepper` Event futx) =
    f x `stepper` Event fut
   where ...
</code></pre>

<p>The initial value is <code>f x</code>, and the change event occurs each time <em>either</em> the function or the argument changes.  If the function changes first, we will (in the future) apply a new reactive function to an old argument:</p>

<pre><code>           fmap ( rf' -&gt; rf' &lt;*&gt; rx) futf
</code></pre>

<p>Similarly, if the argument changes first, we will apply an old reactive function and a new argument:</p>

<pre><code>           fmap ( rx' -&gt; rf &lt;*&gt; rx') futx
</code></pre>

<p>Combining these two futures as alternatives:</p>

<pre><code>...
     fut = fmap ( rf' -&gt; rf' &lt;*&gt; rx ) futf `mappend`
           fmap ( rx' -&gt; rf  &lt;*&gt; rx') futx
</code></pre>

<p>A wonderful thing about this <code>(&lt;*&gt;)</code> definition for Reactive is that it automatically caches the previous value of the function or argument when the argument or function changes.  This caching property is especially handy in nested applications of <code>(&lt;*&gt;)</code>, which can arise either explicitly or through <code>liftA2</code>, <code>liftA3</code>, etc.  Consider <code>u == liftA2 f r s</code> or, equivalently, <code>u == pure f &lt;*&gt; r &lt;*&gt; s</code>, where <code>r</code> and <code>s</code> are reactive values, with initial values <code>r0</code> and <code>s0</code>, respectively.  (The <code>(&lt;*&gt;)</code> operator is associates to the left.)  The initial value <code>u0</code> of <code>u</code> is <code>f r0 s0</code>.  If <code>r</code> changes from <code>r0</code> to <code>r1</code>, then the new value of <code>pure f &lt;*&gt; r</code> will be <code>f r1</code>, which then gets applied to <code>s0</code>, i.e., <code>u1 == f r1 s0</code>.  However, if instead <code>s</code> changes from <code>s0</code> to <code>s1</code>, then <code>u1 == f r0 s1</code>.  In this latter case, the old value <code>f r0</code> of <code>pure f &lt;*&gt; r</code> is passed on without having to be recomputed.  The savings is significant for functions that do some work based partial applications.</p>

<h3>Monad</h3>

<p>Above we saw a simple definition of <code>switcher</code>:</p>

<pre><code>r `switcher` er = join (r `stepper` er)
</code></pre>

<p>How does <code>join</code> work for <code>Reactive</code>?  Rather than using the standard definition of <code>join</code> in terms of <code>(&gt;&gt;=)</code>, let&#8217;s do the reverse:</p>

<pre><code>r &gt;&gt;= h = joinR (fmap h r)
</code></pre>

<p>where <code>joinR</code> is <code>join</code> for reactive values:</p>

<pre><code>joinR :: Reactive (Reactive a) -&gt; Reactive a
</code></pre>

<p>Defining <code>joinR</code> is similar to <code>(&lt;*&gt;)</code> above.  For a reactive-reactive value <code>rr</code>, either <code>rr</code> or the reactive value that is the initial value of <code>rr</code> changes first.</p>

<pre><code>joinR ((a `Stepper` Event fut) `Stepper` e'@(Event fut')) =
  a `stepper` Event fut''
 where
   -- If fut  arrives first, switch and continue waiting for e'.
   -- If fut' arrives first, abandon fut and keep switching with new
   -- reactive values from fut'.
   fut'' = fmap (`switcher` e') fut `mappend` fmap join fut'
</code></pre>

<h2>Dynamic optimization</h2>

<p>Operations on events and reactive values dynamically re-optimize themselves.  For instance, the reactive value <code>fmap f r</code> is known to quiesce (stop changing) when <code>r</code> quiesces, which is knowable because futures have a special representation for the future that never comes.  (Really, only easy common cases are optimized.  An example of a hard-to-detect never-occuring event would be filtering out first the odd numbers and then the even numbers from an <code>Int</code>-valued event.)  Similarly, the reactive value <code>liftA2 f r s</code> quiesces once <em>both</em> <code>r</code> and <code>s</code> quiesce.  Once reactive values quiesce, no more computational resource is devoted to them.</p>

<h2>Events</h2>

<p>The definitions above are mainly for reactive values.  What about functional events?</p>

<h3>Monoid</h3>

<p>Events form a monoid: <code>mempty</code> is the never-occurring event, which is represented by the never-occuring future, while <code>e `mempty` e'</code> is an event consisting of all occurrences from <code>e</code> and <code>e'</code>.</p>

<pre><code>instance Monoid (Event a) where
  mempty  = Event mempty
  Event fut `mappend` Event fut' = Event (fut `merge` fut')
</code></pre>

<p>This <code>merge</code> operation combines two <code>Future</code> streams into one.</p>

<pre><code>merge :: Future (Reactive a) -&gt; Future (Reactive a) -&gt; Future (Reactive a)
Never `merge` fut   = fut
fut   `merge` Never = fut
u     `merge` v     =
  (onFut (`merge` v) &lt;$&gt; u) `mappend` (onFut (u `merge`) &lt;$&gt; v)
 where
   onFut f (a `Stepper` Event t') = a `stepper` Event (f t')
</code></pre>

<p>The <code>mappend</code> used in the definition of <code>merge</code> is from <code>Future</code>.  It picks the earlier future and abandons the other.  Thus the first of the two events to occur will contribute an occurrence value (<code>a</code>), leaving a residual event, which is combined with the not-yet-occurring event.</p>

<h3>Applicative and Monad</h3>

<p>The <code>Applicative</code> and <code>Monad</code> instances for events are like those for lists, and unlike those for reactive values (given above).  For instance, the occurrences of <code>ef &lt;*&gt; ex</code> consist of <code>f x</code> for all occurrences <code>f</code> of <code>ef</code> and occurrences <code>x</code> of <code>ex</code>.  See the <a href="http://darcs.haskell.org/packages/reactive/doc/html/src/Data-Reactive.html">source code</a> for details.</p>

<h2>Conclusion</h2>

<p>I&#8217;m happy with the simplicity of this new functional formulation of events and reactive values.  While most previous FRP implementations used polling, Reactive is change-driven and so has the can be much more efficient.  It also uses a dynamically self-optimizing representation.</p>
<p><a href="http://conal.net/blog/?flattrss_redirect&amp;id=10&amp;md5=dfc295c91e045cfb95ed14f766d2b737"><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/reactive-normal-form/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%2Freactive-normal-form&amp;language=en_GB&amp;category=text&amp;title=Reactive+normal+form&amp;description=The+post+%26%238220%3BReactive+values+from+the+future%26%238221%3B+presented+a+simple+formulation+of+functional+events+and+reactive+values%2C+built+on+a+functional+notion+of+future+values.+In+the+current+post%2C+I%26%238217%3Bll...&amp;tags=events%2Cfuture+value%2Cnormal+form%2Creactive+value%2Creactivity%2Cblog" type="text/html" />
	</item>
		<item>
		<title>Reactive values from the future</title>
		<link>http://conal.net/blog/posts/reactive-values-from-the-future</link>
		<comments>http://conal.net/blog/posts/reactive-values-from-the-future#comments</comments>
		<pubDate>Fri, 25 Jan 2008 21:56:36 +0000</pubDate>
		<dc:creator><![CDATA[Conal]]></dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[future value]]></category>
		<category><![CDATA[reactive value]]></category>
		<category><![CDATA[reactivity]]></category>

		<guid isPermaLink="false">http://conal.net/blog/posts/reactive-values-from-the-future/</guid>
		<description><![CDATA[I&#8217;ve gotten interested lately in revisiting functional reactive programming (FRP). I was never entirely satisfied with the semantics or implementation in my original Fran formulation or in its successors. Over the last year, I&#8217;ve enjoyed getting more interface and functionality from standard type classes, and I&#8217;ve realized that quite a lot of FRP could be [&#8230;]]]></description>
				<content:encoded><![CDATA[<!-- 

Title: Reactive values from the future

Tags: reactivity, future values, reactive values, events

-->

<!-- references -->

<!-- teaser -->

<p>I&#8217;ve gotten interested lately in revisiting functional reactive programming (FRP).  I was never entirely satisfied with the semantics or implementation in my original <a href="http://conal.net/Fran" title="Fran -- functional reactive animation">Fran</a> formulation or in its successors.  Over the last year, I&#8217;ve enjoyed getting more interface and functionality from standard type classes, and I&#8217;ve realized that quite a lot of FRP could be both packaged and implemented by leveraging those classes.  This post describes that packaging, and in particular shows how the <code>Monad</code> interface makes some operations very easy to define.  I suspect that monadic functional reactivity is a very powerful structuring tool with lovely applications.</p>

<p>At <a href="http://www.informatik.uni-bonn.de/~ralf/icfp07.html" title="International Conference on Functional Programming, 2007">ICFP 07</a>, I had a conversation with <a href="http://www.deinprogramm.de/sperber/" title="Home page: Mike Sperber">Mike Sperber</a> about FRP and about his FRP-based <a href="http://www-pu.informatik.uni-tuebingen.de/lula" title="The Lula system for lighting design and control">Lula</a> system for stage lighting.  Mike used blocking threads in Lula, which I had never considered for FRP.  While playing with the idea, I realized that I could give a very elegant and efficient solution to caching, unlike my previous FRP implementations, including the recent <a href="http://haskell.org/haskellwiki/DataDriven" title="Wiki page on the DataDriven library">DataDriven</a> library.  From there, I stumbled on the idea of <em>reactive normal form</em> and separating out an aspect of reactivity into the notion of <em><a href="http://conal.net/blog/posts/future-values/" title="Blog post: &quot;Future values&quot;">future values</a></em>.  A third new (to me) idea is to factor out continuity from reactivity, so that <em>reactive behaviors</em> arise by composing orthogonal notions of <em>reactive values</em> and non-reactive functions of continuous time.</p>

<p>Two previous posts presented <em>future values</em>, first describing <a href="http://conal.net/blog/posts/future-values/" title="Blog post: &quot;Future values&quot;">interface and semantics</a> and then a <a href="http://conal.net/blog/posts/future-values-via-multi-threading/" title="Blog post: &quot;Future values via multi-threading&quot;">multi-threaded implementation</a>.  This post builds a simple foundation for FRP on top of future values, as part of a library <a href="http://haskell.org/haskellwiki/Reactive" title="Wiki page for the Reactive library">Reactive</a>.</p>

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

<h2>Functional events and reactive values</h2>

<p>A functional <em>event</em> is (semantically) a stream of time-associated values, ordered with respect to time.  For example, the stream of keystrokes you&#8217;ll type.  While many systems have a primitive notion of events, functional events are <em>compositional</em>, i.e., they&#8217;re constructed by applying operations to one or more simpler events, e.g., the lower-case version of your keystroke stream, the substream of uppercase keys, or the temporally interleaved stream from your keystrokes <em>and</em> mine (data massaging, filtering, and merging).  As usual, compositionality leads to reuse.</p>

<p>A <em>reactive value</em> is a functional notion for a value that changes discretely over time, based on the occurrences of one or more (possibly composite) events.  Reactive values provide a a first class encapsulation of the infinite time-line of varying values.  As such, they replace many of the uses of imperative programming, particularly concurrent imperative programming, which is notoriously difficult to work with and reason about.</p>

<p>The semantics of a reactive value can be simply a function of time.  Since reactive values change <em>discretely</em> (though see below for continuous change), their meanings will be step functions (changing only at a discrete&#8211;but possibly infinite&#8211;set of domain values).  Since a step function is fully defined by an initial value and a discrete set of time-associated values (the changes), we can represent reactive values as a value plus an event that yields more values over time.</p>

<pre><code>data Reactive a = Stepper a (Event a)
</code></pre>

<p>How then might we define <code>Event</code>?  It is a stream of a first occurrence and some more occurrences, just like <code>Reactive</code>.  But the first occurrence and the remainder event are knowable only in the future.  Therefore,</p>

<pre><code>newtype Event a = Future (Reactive a)
</code></pre>

<p>using the <code>Future</code> type described in <a href="http://conal.net/blog/posts/future-values/" title="Blog post: &quot;Future values&quot;">a previous post</a>.</p>

<h2>Composing reactivity</h2>

<h3>Standard classes</h3>

<p>Many of the means of constructing events and reactive values are packaged as methods on the standard type classes <code>Monoid</code>, <code>Functor</code>, <code>Applicative</code>, and <code>Monad</code>.  See the Reactive <a href="http://haskell.org/haskellwiki/Reactive" title="Wiki page for the Reactive library">wiki page</a> and <a href="http://darcs.haskell.org/packages/reactive/doc/html" title="Library documentation for Reactive">documentation</a> for descriptions of these instances.  Here are a few examples:</p>

<ul>
<li>The event <code>e `mappend` e'</code> occurs whenever <code>e</code> or <code>e'</code> occurs.</li>
<li>The event <code>fmap f e</code> (also called <code>f &lt;$&gt; e</code>) occurs with value <code>f x</code> whenever <code>e</code> occurs with value <code>x</code>.</li>
<li>The reactive value <code>rf &lt;*&gt; rx</code> at time <code>t</code> is equal has value <code>f x</code>, where <code>rf</code> and <code>rx</code> have the values <code>f</code> and <code>x</code> respectively at time <code>t</code>.  The <code>(&lt;*&gt;)</code> and <code>pure</code> functions (the methods of <code>Applicative</code>) are the basis of applying an <em>n</em>-ary function to <em>n</em> reactive values, to form a reactive value.  Note the implicit and semantically simple concurrency.</li>
<li>If <code>ee</code> is an event-valued event (<code>ee :: Event (Event a)</code>), then <code>join ee</code> is an event whose occurrences are all of the occurrences of all of the events in <code>ee</code>.</li>
</ul>

<h3>Switching</h3>

<p>The main tools for introducing reactivity are <code>stepper</code> and <code>switcher</code>.  (These combinators were <a href="http://conal.net/papers/dsl97" title="Paper: &quot;Modeling Interactive 3D and Multimedia Animation with an Embedded Language&quot;">added to Fran</a> after the <a href="http://conal.net/papers/icfp97/">original paper</a>, which had only single-shot events and therefore encouraged an explictly recursive programming style.)  The <code>stepper</code> function exactly corresponds to the <code>Stepper</code> constructor in our our new representation of <code>Reactive</code> above.</p>

<pre><code>stepper :: a -&gt; Event a -&gt; Reactive a
stepper = Stepper
</code></pre>

<p>For a more general reactive combinator, <code>switcher</code> takes an initial <em>reactive value</em> and an event that generates reactive values to switch to.</p>

<pre><code>switcher :: Reactive a -&gt; Event (Reactive a) -&gt; Reactive a
</code></pre>

<p>Pleasantly, it is very easy to define this general form of switching in terms of the simpler <code>stepper</code>.  To see how this definition works, note that the arguments of <code>switcher</code> are also suitable as arguments to <code>stepper</code>, but the result will be of type <code>Reactive (Reactive a)</code> instead of <code>Reactive a</code>.  Fortunately, <code>Reactive</code> is a monad, so <code>join</code> turns reactive-reactive values into reactive values.</p>

<pre><code>r `switcher` er = join (r `stepper` er)
</code></pre>

<h3>Other building blocks</h3>

<p>Many other event and reactive value combinators are described in the Reactive <a href="http://darcs.haskell.org/packages/reactive/doc/html" title="Library documentation for Reactive">library docs</a>.  Here are just a few:</p>

<ul>
<li>Cumulative application of functions from a function-valued event.</li>
<li>A <code>scanl</code> for events and one for values.</li>
<li>Filtering of <code>Maybe</code>-valued events, and filtering of an event by a boolean reactive value.</li>
<li>Sampling of a reactive value at each occurrence of an event.</li>
</ul>

<h2>Coming attractions</h2>

<p>Future posts will (a) present the implementation of events and reactive values via a <a href="http://conal.net/blog/posts/reactive-normal-form/" title="Blog post: &quot;Reactive normal form&quot;">reactive normal form</a>, and (b) say how to <a href="http://conal.net/blog/posts/blending-continuity-into-reactive-values/" title="Blog post: &quot;Blending continuity into reactive values&quot;">blend temporal continuity</a> with our discrete notion of reactive values.</p>

<p>I see FRP as being a viable alternative to imperative programming, especially with concurrency.  Like the imperative programming model, FRP is about change.  Unlike concurrent imperative programming, FRP has formally tractable&#8211;even simple&#8211;semantics.  Future blog posts will give examples of how to reduce dependence on side-effects, widening the pure, and hence semantically tractable and composable, core of programs.</p>

<hr />

<p><em>Edit 2008-02-07:</em> added missing type parameter in <code>Event</code> definition.</p>
<p><a href="http://conal.net/blog/?flattrss_redirect&amp;id=9&amp;md5=1f22bc6a562564cb485179f7d0c9b8fe"><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/reactive-values-from-the-future/feed</wfw:commentRss>
		<slash:comments>7</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%2Freactive-values-from-the-future&amp;language=en_GB&amp;category=text&amp;title=Reactive+values+from+the+future&amp;description=I%26%238217%3Bve+gotten+interested+lately+in+revisiting+functional+reactive+programming+%28FRP%29.+I+was+never+entirely+satisfied+with+the+semantics+or+implementation+in+my+original+Fran+formulation+or+in+its+successors.+Over...&amp;tags=events%2Cfuture+value%2Creactive+value%2Creactivity%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>
