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

<channel>
	<title>Less Sugar/More Meat</title>
	<atom:link href="http://netsuperbrain.com/blog/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://netsuperbrain.com/blog</link>
	<description>Sankel Software, FRP, Haskell, Reactive</description>
	<pubDate>Mon, 20 Jun 2011 18:31:39 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.6.2</generator>
	<language>en</language>
			<item>
		<title>Haskell&#8217;s evaluation isn&#8217;t magic</title>
		<link>http://netsuperbrain.com/blog/posts/haskells-evaluation-isnt-magic/</link>
		<comments>http://netsuperbrain.com/blog/posts/haskells-evaluation-isnt-magic/#comments</comments>
		<pubDate>Mon, 20 Jun 2011 18:30:28 +0000</pubDate>
		<dc:creator>pipoca</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://netsuperbrain.com/blog/?p=371</guid>
		<description><![CDATA[One common complaint with lazy functional programming is that reasoning about the performance of your code is harder than in a strict language.  Will an expression be repeatedly evaluated or a closure repeatedly accessed?  Will code use up more or less heap space?  For that matter, many people have no clue as [...]]]></description>
			<content:encoded><![CDATA[<p>One common complaint with lazy functional programming is that reasoning about the performance of your code is harder than in a strict language.  Will an expression be repeatedly evaluated or a closure repeatedly accessed?  Will code use up more or less heap space?  For that matter, many people have no clue as to how lazy evaluation works in the first place.<br />
<span id="more-371"></span>
<img src="http://netsuperbrain.com/img/frusteratedLady.jpg" alt="Frustrated Lady" /></p>

<p>This blog post show that execution in a lazy language is both understandable and predictable.</p>

<p>Haskell is in essence a heavily sugared and extended version of a typed λ-calculus (i.e. λ-calculus with a type system attached).  If you don&#8217;t understand simple λ-calculus, you should read a tutorial, such as the first two chapters of <a href="ftp://ftp.cs.ru.nl/pub/CompMath.Found/lambda.pdf">Introduction to Lambda Calculus[pdf]</a>.  We won&#8217;t be doing anything too complicated with it, but you should understand the basic syntax and ideas behind it.  If we want to understand Haskell&#8217;s execution, we should should first understand call-by-need evaluation of λ-calculus.</p>

<p>In 1993 Launchbury wrote <a href="http://citeseer.ist.psu.edu/viewdoc/download;jsessionid=4BD17FFFBAFCFFE1026C038702BA72E5?doi=10.1.1.35.2016&amp;rep=rep1&amp;type=pdf">A Natural Semantics for Lazy Evaluation [pdf]</a>, which provided a simple operational semantics (I&#8217;ll explain what that is in a second) for understanding the lazy evaluation of an extended λ-calculus.  The most important extension is the let statements: “lets are irreplaceable in lazy functional programming in that they may create cyclic structures in the heap.  This cannot be achieved without them (or without something essentially equivalent), and cyclic structures have a huge implication for the amount of computation that may be performed” .  He also includes constructors, case statements, and primitives in an extension to the base semantics.  Operational semantics is very appropriately named:  it provides <i>semantics</i>, or a meaning, to the code in terms of its <i>operation</i> on some abstract machine.  What precisely is an abstract machine?  Basically, it&#8217;s a mathematical model of a machine.   Rather than create a physical machine with moving or electronic parts, you create a transition function.  This function takes the current state (e.g. the current heap, stack, and the expression you want to reduce), and produces the next state (say, the heap remained the same, but you pushed something onto the stack and you&#8217;re evaluating some subexpression).  Launchbury&#8217;s semantics are reasonably high-level and simple, but still capture sharing and heap usage.</p>

<p>Before we continue, let&#8217;s remind ourselves how the λ-calculus is evaluated.  There are several strategies for reducing a λ-term, which have different pros and cons. In normal order reduction, the outermost leftmost redex (reducible expression, i.e. something of the form (λx.y)z is reduced.  This means that you don&#8217;t evaluate the arguments to a function until after they&#8217;re plugged into the function.  Call-by-name is similar to normal order, except that you don&#8217;t reduce anything inside a λ-abstraction.  Call-by-need is very similar to call-by-name, but with one key difference:  call-by-name implements sharing (I&#8217;ll explain what that is momentarily).  Call-b-name and call-by-need stand in contrast with call-by-value reduction, where you reduce the outermost redex only after you reduce its right hand side (i.e.  the arguments to the function get evaluated before the function does).</p>

<p>What does sharing mean?  It means that arguments to a function are only evaluated once; the calculated values are “shared” between their uses.  For example, consider the expression (λx. mult x x) (<a href="http://en.wikipedia.org/wiki/Ackermann_function">ackermann</a> 4 1).  Under call-by-value, you first reduce this to (λx. mult x x) 65533, and then to mult 65533 65533, then to 4,294,574,089.  In call-by-name, you first reduce it to mult (ackermann 4 1) (ackermann 4 1).  You then evaluate (ackermann 4 1) twice, because it appears twice.  Call-by-need gets rid of this repeated evaluation: the first time you evaluate (ackermann 4 1), you replace both occurrences of it with 65533.  Obviously, this is a very important optimization.  It&#8217;s important to point out here that sharing doesn&#8217;t mean Common Subexpression Elimination; it only means that arguments are evaluated only once.</p>

<p>Before you can apply the reduction rules, Launchbury&#8217;s semantics require a term to be normalized.  A Launchbury-normalized term is one in which every name is unique (so scope isn&#8217;t important because something in an inner scope cannot shadow something in an outer scope), and which every application involves applying a variable to an expression.  Normalization is simple: just replace every variable with a fresh variable (so everything becomes distinctly named), and replace constructs of the form &#8220;e1 e2&#8243; with &#8220;let x = e2 in e1 x&#8221;.  So, in our previous example, (λx. mult x x) (ackermann 4 1) is normalized to let z = expensive 4 1 in (λx.  mult x x) z.  Since we will store our let-bound variables on the heap, this means that implementing sharing is trivial: we update the reference on the heap the first time we evaluate it, and just use that value every other time.</p>

<p>In order to help illustrate the semantics, I&#8217;ve written up a small interpreter which takes in a normalized expression and reduces it, returning both the reduced expression and a log of how it got there.  I didn&#8217;t implement a normalizer; instead expressions need to be normalized by hand.</p>

<p>Let&#8217;s go over the interpreter.  I&#8217;ll leave out constructors, primitives and case statements, although they&#8217;re on <a href="http://hackage.haskell.org/package/TinyLaunchbury">hackage</a>.  I&#8217;ll also leave out the implementation of the various helper functions; their details aren&#8217;t important to understanding the semantics.</p>

<p>To start out with, we should define some types to represent an expression:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">type</span> Name <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #cccc00; font-weight: bold;">String</span> 
&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Expr <span style="color: #339933; font-weight: bold;">=</span>  Lambda Name Expr
           | Apply Expr Name
           | Var Name
           | Let Bindings Expr
           <span style="color: #06c; font-weight: bold;">deriving</span> <span style="color: green;">&#40;</span><span style="color: #cccc00; font-weight: bold;">Eq</span><span style="color: #339933; font-weight: bold;">,</span> <span style="color: #cccc00; font-weight: bold;">Show</span><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Binding <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span>Name<span style="color: #339933; font-weight: bold;">,</span>Expr<span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">type</span> Bindings <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#91;</span>Binding<span style="color: green;">&#93;</span><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Heap <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span>Var<span style="color: #339933; font-weight: bold;">,</span> Expr<span style="color: green;">&#41;</span><span style="color: green;">&#93;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> ReduceM a <span style="color: #339933; font-weight: bold;">=</span>  <span style="color: #339933; font-weight: bold;">...</span>
&nbsp;
<span style="color: #5d478b; font-style: italic;">--record that current state</span>
<span style="color: #06c; font-weight: bold;">data</span> ReduceState <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #339933; font-weight: bold;">...</span></pre></div></div>


<p>Expr is fairly simple:  It represents the syntax tree of lambda expressions extended with let.  We&#8217;ll represent variables as strings, because it&#8217;s convenient.  A Heap, with respect to the paper, is &#8220;a partial function from variables to expressions&#8221;, however, you can also think of it as &#8220;an unordered set of variable/expression pairs, binding distinct variable names to expressions&#8221;.  The latter interpretation is easier to work with, so we&#8217;ll be using it.  I&#8217;m leaving out the implementation of Show, but the Hackage code includes an instance of show that outputs reasonable looking code.  ReduceM keeps track of the state of the heap, the fresh variables, and the log, as well as allowing reduce to fail.</p>

<p>Here are the functions to make working with ReduceM reasonable:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">&nbsp;
&nbsp;
rmRun <span style="color: #339933; font-weight: bold;">::</span> ReduceM a → ReduceState → <span style="color: green;">&#40;</span><span style="color: #cccc00; font-weight: bold;">Either</span> <span style="color: #cccc00; font-weight: bold;">String</span> a<span style="color: #339933; font-weight: bold;">,</span> ReduceState<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- hides the implementation detail of failing; makes it easier to</span>
<span style="color: #5d478b; font-style: italic;">-- swap out the underlying monad.</span>
rmErr <span style="color: #339933; font-weight: bold;">::</span> <span style="color: #cccc00; font-weight: bold;">String</span> → ReduceM Expr
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- |Like sub, but for a list of things to substite</span>
<span style="color: #5d478b; font-style: italic;">-- useful for implementing recursive lets (i.e. letrec)</span>
subs <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span>Name<span style="color: #339933; font-weight: bold;">,</span>Name<span style="color: green;">&#41;</span><span style="color: green;">&#93;</span> → <span style="color: green;">&#40;</span>Expr → Expr<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- |e[x/y] in Launchbury's notation</span>
<span style="color: #5d478b; font-style: italic;">--  [x ↦ y]e in Pierce's notation in TaPL</span>
<span style="color: #5d478b; font-style: italic;">--  recursively descend expression tree to substitute a free variable</span>
sub <span style="color: #339933; font-weight: bold;">::</span>  Name → Name → <span style="color: green;">&#40;</span>Expr → Expr<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- |freshen takes an expression, and returns the same expression with every </span>
<span style="color: #5d478b; font-style: italic;">-- bound variable substituted for a fresh variable. </span>
freshen <span style="color: #339933; font-weight: bold;">::</span> Expr → ReduceM Expr
&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> ErrorOr a <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #cccc00; font-weight: bold;">Either</span> <span style="color: #cccc00; font-weight: bold;">String</span> a
<span style="color: #06c; font-weight: bold;">type</span> Log <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #cccc00; font-weight: bold;">String</span>
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- look up a binding on the heap</span>
heapLookup <span style="color: #339933; font-weight: bold;">::</span> Name → ReduceM Expr
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- remove a binding from the heap</span>
heapRemove <span style="color: #339933; font-weight: bold;">::</span> Name → ReduceM <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- create a new binding on the heap</span>
heapAdd <span style="color: #339933; font-weight: bold;">::</span> Name → Expr → ReduceM <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #5d478b; font-style: italic;">--  get the next fresh variable.  Fresh variables are of the form $23, for random</span>
<span style="color: #5d478b; font-style: italic;">-- values of 23</span>
getFreshVar <span style="color: #339933; font-weight: bold;">::</span> ReduceM Name
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- reduces an expression.</span>
reduceM <span style="color: #339933; font-weight: bold;">::</span> Expr → ReduceM Expr</pre></div></div>


<p>Freshen and sub are important, but the real work of the program is done in reduceM; that&#8217;s where the reduction actually happens.  So what does the code for it look like?</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">reduceM <span style="color: #339933; font-weight: bold;">::</span> Expr → ReduceM Expr
reduceM e <span style="color: #339933; font-weight: bold;">=</span>
    <span style="color: #06c; font-weight: bold;">case</span> e <span style="color: #06c; font-weight: bold;">of</span>
        Lambda e' x → <span style="font-weight: bold;">return</span> <span style="color: green;">&#40;</span>Lambda e' x<span style="color: green;">&#41;</span>  
        Apply e' x  →  <span style="color: #06c; font-weight: bold;">do</span> Lambda y' e'' ← reduceM e'
                          reduceM <span style="color: green;">&#40;</span>sub y' x e''<span style="color: green;">&#41;</span>
        Var x →       <span style="color: #06c; font-weight: bold;">do</span> e' ← heapLookup x
                         heapRemove x
                         z ← reduceM e'
                         heapAdd x z
                         freshen z
        Let bs e' →  <span style="color: #06c; font-weight: bold;">do</span> <span style="font-weight: bold;">mapM_</span> <span style="color: green;">&#40;</span><span style="font-weight: bold;">uncurry</span> heapAdd<span style="color: green;">&#41;</span> bs
                        reduceM e'</pre></div></div>


<p>Let&#8217;s go through each of these cases one by one.</p>

<p>First: Lambda.  The only sensible thing to do here is to just return the λ-abstraction, because we&#8217;re not allowed to reduce inside of a λ-abstraction.</p>

<p>Second: Apply.  In order to actually apply a variable to a subexpression, we need a function to apply it to.  However, the subexpression might not be a λ-abstraction.  Instead, it could be something that returns a λ-abstraction – a variable, a let, or even another apply!  The only sensible thing to do here is to reduce our subexpression, and then apply the variable to it.</p>

<p>Third: Variable.  In order to reduce a variable x, we must first know what it is bound to on the heap.  So, we look up the expression e that it is bound to.  The next step is less obvious: we reduce e with x&#8217;s binding removed from the heap, before returning a freshened version of the result, to avoid unwanted variable capture.  Is this correct?</p>

<p>Obviously, if the expression isn&#8217;t recursive, we&#8217;re fine – it&#8217;s never going to look at its own binding.  What happens in that case if x is recursive?  Well, there are two possibilities – either the sub-expression depends on itself before it reduces, or it depends on itself after it reduces.  If it depends on itself after it reduces, then we&#8217;re obviously fine – the binding will already be back on the heap. What about the other case?  We&#8217;re actually still fine:  If you depend on yourself before you reduce to a value, then you must be an infinite loop.  In this case, we fail outright, because we&#8217;re trying to look up a binding which doesn&#8217;t exist. Failing outright and having an infinite loop are the same thing, semantically speaking, so we&#8217;re actually still fine.</p>

<p>Here&#8217;s some examples of recursion, both good and bad. Assume the appropriate functions have been defined for the third example.  It also hasn&#8217;t been properly normalized, but ignore that as well.  Can you figure out what these will do?  The answers will be at the bottom of the post
<pre>
let x = x in x 
let f = λx.f x in f 2
let len = λlist. if (empty? list) 0 (1 + (len (cdr list))) in len some-list
</pre></p>

<p>Fourth: Let.  Since everything is distinctly named, we don&#8217;t need to worry about scope; names will never clash because each name can only be used once.  Therefore, it&#8217;s obviously correct to just add the bindings to the heap.</p>

<p>Now that we&#8217;ve explained this, let&#8217;s look at the output of some runthroughs:</p>


<div class="wp_syntax"><div class="code"><pre class="foo" style="font-family:monospace;">Reducing let: let u = 3 + 2, v = u + 1 in v + v : {}</pre></div></div>


<p>How should we interpret this?  Well, it&#8217;s fairly simple.  In the beginning,we start to reduce the expression &#8216;let u = 3 + 2, v = u + 1 in v + v&#8217;, using an empty heap (denoted &#8216;{}&#8217;).</p>


<div class="wp_syntax"><div class="code"><pre class="foo" style="font-family:monospace;">|Reducing primitive: v + v : {v → u + 1, u → 3 + 2}</pre></div></div>


<p>We then add the bindings to the heap and take a look at the addition &#8216;v + v&#8217;.</p>


<div class="wp_syntax"><div class="code"><pre class="foo" style="font-family:monospace;">||Reducing variable: v : {v → u + 1, u → 3 + 2}</pre></div></div>


<p>In order to reduce &#8216;v + v&#8217;, you first need to evaluate v.</p>


<div class="wp_syntax"><div class="code"><pre class="foo" style="font-family:monospace;">|||Reducing primitive: u + 1 : {u → 3 + 2}
||||Reducing variable: u : {u → 3 + 2}</pre></div></div>


<p>To calculate v, we need to evaluate u.</p>


<div class="wp_syntax"><div class="code"><pre class="fool" style="font-family:monospace;">|||||Reducing primitive: 3 + 2 : {}
||||||Returning constructor: 3 : {}
||||||Returning constructor: 2 : {}
|||||Primitive evaluated to 5
||||Rebinding var u to 5
||||Returning constructor: 1 : {u → 5}
|||Primitive evaluated to 6
||Rebinding var v to 6</pre></div></div>


<p>So we evaluate u, then evaluate v with the result of u.</p>


<div class="wp_syntax"><div class="code"><pre class="fool" style="font-family:monospace;">||Reducing variable: v : {v → 6, u → 5}</pre></div></div>


<p>We&#8217;re re-grabbing v here for the second usage of v in v+v</p>


<div class="wp_syntax"><div class="code"><pre class="foo" style="font-family:monospace;">|||Returning constructor: 6 : {u → 5}
||Rebinding var v to 6
|Primitive evaluated to 12
Ans: 12</pre></div></div>


<p>Note that we access v two times in this, but we only access u a single time.</p>

<p>For another two test cases, let&#8217;s take a look at two examples from Launchbury&#8217;s paper:</p>

<p>First: let u = 2 + 3, f = \x.let v = u + 1 in v + x, a = 2, b = 3 in f a
+ f b</p>

<p>and</p>

<p>Second: let u = 2 + 3, f = let v = u + 1 in \x.v + x, a = 2, b = 3 in f a
+ f b</p>

<p>Note that the expressions are the same except for f&#8217;s definition; in the first, f is &#8220;\x.let v = u + 1 in v + x,&#8221; and in the second f is &#8220;let v = u + 1 in \x.v + x&#8221;.  Obviously, these two are going to evaluate to the same thing.  However, what&#8217;s going to be the difference in terms of how they reduce?  Does one share sub-computations more effectively than the other to reduce the amount of computation needed?  Let&#8217;s take a look at the log produced by running them to figure that out.</p>


<div class="wp_syntax"><div class="code"><pre class="foo" style="font-family:monospace;">Reducing let: let u = 2 + 3, f = \x.let v = u + 1 in v + x, a = 2, b = 3 in f a + f b : {}
|Reducing primitive: f a + f b : {b → 3, a → 2, f → \x.let v = u + 1 in v + x, u → 2 + 3}
||Reducing apply: f a : {b → 3, a → 2, f → \x.let v = u + 1 in v + x, u → 2 + 3}
|||Reducing variable: f : {b → 3, a → 2, f → \x.let v = u + 1 in v + x, u → 2 + 3}
||||Returning lambda: \x.let v = u + 1 in v + x : {b → 3, a → 2, u → 2 + 3}
|||Rebinding var f to \x.let v = u + 1 in v + x
|||Reducing let: let $2 = u + 1 in $2 + a : {f → \x.let v = u + 1 in v + x, b → 3, a → 2, u → 2 + 3}
||||Reducing primitive: $2 + a : {$2 → u + 1, f → \x.let v = u + 1 in v + x, b → 3, a → 2, u → 2 + 3}
|||||Reducing variable: $2 : {$2 → u + 1, f → \x.let v = u + 1 in v + x, b → 3, a → 2, u → 2 + 3}
||||||Reducing primitive: u + 1 : {f → \x.let v = u + 1 in v + x, b → 3, a → 2, u → 2 + 3}
|||||||Reducing variable: u : {f → \x.let v = u + 1 in v + x, b → 3, a → 2, u → 2 + 3}
||||||||Reducing primitive: 2 + 3 : {f → \x.let v = u + 1 in v + x, b → 3, a - &amp;gt; 2}
|||||||||Returning constructor: 2 : {f → \x.let v = u + 1 in v + x, b → 3, a - &amp;gt; 2}
|||||||||Returning constructor: 3 : {f → \x.let v = u + 1 in v + x, b → 3, a - &amp;gt; 2}
||||||||Primitive evaluated to 5
|||||||Rebinding var u to 5
|||||||Returning constructor: 1 : {u → 5, f → \x.let v = u + 1 in v + x, b → 3, a → 2}
||||||Primitive evaluated to 6
|||||Rebinding var $2 to 6
|||||Reducing variable: a : {$2 → 6, u → 5, f → \x.let v = u + 1 in v + x, b → 3, a → 2}
||||||Returning constructor: 2 : {$2 → 6, u → 5, f → \x.let v = u + 1 in v + x, b → 3}
|||||Rebinding var a to 2
||||Primitive evaluated to 8
||Reducing apply: f b : {a → 2, $2 → 6, u → 5, f → \x.let v = u + 1 in v + x , b → 3}
|||Reducing variable: f : {a → 2, $2 → 6, u → 5, f → \x.let v = u + 1 in v + x, b → 3}
||||Returning lambda: \x.let v = u + 1 in v + x : {a → 2, $2 → 6, u → 5, b → 3}
|||Rebinding var f to \x.let v = u + 1 in v + x
|||Reducing let: let $4 = u + 1 in $4 + b : {f → \x.let v = u + 1 in v + x, a - &amp;gt; 2, $2 → 6, u → 5, b → 3}
||||Reducing primitive: $4 + b : {$4 → u + 1, f → \x.let v = u + 1 in v + x, a → 2, $2 → 6, u → 5, b → 3}
|||||Reducing variable: $4 : {$4 → u + 1, f → \x.let v = u + 1 in v + x, a → 2, $2 → 6, u → 5, b → 3}
||||||Reducing primitive: u + 1 : {f → \x.let v = u + 1 in v + x, a → 2, $2 → 6, u → 5, b → 3}
|||||||Reducing variable: u : {f → \x.let v = u + 1 in v + x, a → 2, $2 → 6, u → 5, b → 3}
||||||||Returning constructor: 5 : {f → \x.let v = u + 1 in v + x, a → 2, $2 → 6, b → 3}
|||||||Rebinding var u to 5
|||||||Returning constructor: 1 : {u → 5, f → \x.let v = u + 1 in v + x, a → 2, $2 → 6, b → 3}
||||||Primitive evaluated to 6
|||||Rebinding var $4 to 6
|||||Reducing variable: b : {$4 → 6, u → 5, f → \x.let v = u + 1 in v + x, a → 2, $2 → 6, b → 3}
||||||Returning constructor: 3 : {$4 → 6, u → 5, f → \x.let v = u + 1 in v + x, a → 2, $2 → 6}
|||||Rebinding var b to 3
||||Primitive evaluated to 9
|Primitive evaluated to 17
Ans: 17
&nbsp;
Reducing let: let u = 2 + 3, f = let v = u + 1 in \x.v + x, a = 2, b = 3 in f a + f b : {}
|Reducing primitive: f a + f b : {b → 3, a → 2, f → let v = u + 1 in \x.v + x , u → 2 + 3}
||Reducing apply: f a : {b → 3, a → 2, f → let v = u + 1 in \x.v + x, u → 2 + 3}
|||Reducing variable: f : {b → 3, a → 2, f → let v = u + 1 in \x.v + x, u → 2 + 3}
||||Reducing let: let v = u + 1 in \x.v + x : {b → 3, a → 2, u → 2 + 3}
|||||Returning lambda: \x.v + x : {v → u + 1, b → 3, a → 2, u → 2 + 3}
|||Rebinding var f to \x.v + x
|||Reducing primitive: v + a : {f → \x.v + x, v → u + 1, b → 3, a → 2, u → 2 + 3}
||||Reducing variable: v : {f → \x.v + x, v → u + 1, b → 3, a → 2, u → 2 + 3}
|||||Reducing primitive: u + 1 : {f → \x.v + x, b → 3, a → 2, u → 2 + 3}
||||||Reducing variable: u : {f → \x.v + x, b → 3, a → 2, u → 2 + 3}
|||||||Reducing primitive: 2 + 3 : {f → \x.v + x, b → 3, a → 2}
||||||||Returning constructor: 2 : {f → \x.v + x, b → 3, a → 2}
||||||||Returning constructor: 3 : {f → \x.v + x, b → 3, a → 2}
|||||||Primitive evaluated to 5
||||||Rebinding var u to 5
||||||Returning constructor: 1 : {u → 5, f → \x.v + x, b → 3, a → 2}
|||||Primitive evaluated to 6
||||Rebinding var v to 6
||||Reducing variable: a : {v → 6, u → 5, f → \x.v + x, b → 3, a → 2}
|||||Returning constructor: 2 : {v → 6, u → 5, f → \x.v + x, b → 3}
||||Rebinding var a to 2
|||Primitive evaluated to 8
||Reducing apply: f b : {a → 2, v → 6, u → 5, f → \x.v + x, b → 3}
|||Reducing variable: f : {a → 2, v → 6, u → 5, f → \x.v + x, b → 3}
||||Returning lambda: \x.v + x : {a → 2, v → 6, u → 5, b → 3}
|||Rebinding var f to \x.v + x
|||Reducing primitive: v + b : {f → \x.v + x, a → 2, v → 6, u → 5, b → 3}
||||Reducing variable: v : {f → \x.v + x, a → 2, v → 6, u → 5, b → 3}
|||||Returning constructor: 6 : {f → \x.v + x, a → 2, u → 5, b → 3}
||||Rebinding var v to 6
||||Reducing variable: b : {v → 6, f → \x.v + x, a → 2, u → 5, b → 3}
|||||Returning constructor: 3 : {v → 6, f → \x.v + x, a → 2, u → 5}
||||Rebinding var b to 3
|||Primitive evaluated to 9
|Primitive evaluated to 17
Ans: 17</pre></div></div>


<p>As you can immediately see, the first one has a larger heap than the second one does.  The reason for that becomes clear when you look at it more closely:  In the second one, when we reduce f we add the let bindings to the heap once, because it&#8217;s outside the enclosing lambda.  In the first one, on the other hand, f doesn&#8217;t reduce at all, because the lambda is the outermost thing.  On account of that, we end up adding &#8220;v = u + 1&#8243; to the heap twice in the first case, which leads to performing that calculation twice.  In the second expression, on the other hand, v is added to the heap the first time we call f, so both invocations share the same heap space for v, which means that u is only accessed a single time.</p>

<p>Based off of those logs, it is reasonable to expect that the first expression will run faster.  So, lets test that.  Here are those two functions, translated straightforwardly into Haskell.  We&#8217;ll run them in Hugs, since Hugs will print the number of heap cells used and reductions made.  Smaller numbers for both are better.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">slowExprHaskell <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #06c; font-weight: bold;">let</span> u <span style="color: #339933; font-weight: bold;">=</span> <span style="color: red;">3</span><span style="color: #339933; font-weight: bold;">+</span><span style="color: red;">2</span>
                      f <span style="color: #339933; font-weight: bold;">=</span> \x → <span style="color: #06c; font-weight: bold;">let</span> v <span style="color: #339933; font-weight: bold;">=</span> u<span style="color: #339933; font-weight: bold;">+</span><span style="color: red;">1</span> <span style="color: #06c; font-weight: bold;">in</span> v <span style="color: #339933; font-weight: bold;">+</span> x
                  <span style="color: #06c; font-weight: bold;">in</span> f <span style="color: red;">2</span> <span style="color: #339933; font-weight: bold;">+</span> f <span style="color: red;">3</span>
&nbsp;
fastExprHaskell <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #06c; font-weight: bold;">let</span> u <span style="color: #339933; font-weight: bold;">=</span> <span style="color: red;">3</span><span style="color: #339933; font-weight: bold;">+</span><span style="color: red;">2</span>
                      f <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #06c; font-weight: bold;">let</span> v <span style="color: #339933; font-weight: bold;">=</span> u<span style="color: #339933; font-weight: bold;">+</span><span style="color: red;">1</span> <span style="color: #06c; font-weight: bold;">in</span> \x → v <span style="color: #339933; font-weight: bold;">+</span> x
                  <span style="color: #06c; font-weight: bold;">in</span> f <span style="color: red;">2</span> <span style="color: #339933; font-weight: bold;">+</span> f <span style="color: red;">3</span>
–<span style="color: #339933; font-weight: bold;">-</span> results from Hugs:
Main<span style="color: #339933; font-weight: bold;">$</span> slowExprHaskell
<span style="color: red;">17</span>
<span style="color: green;">&#40;</span><span style="color: red;">47</span> reductions<span style="color: #339933; font-weight: bold;">,</span> <span style="color: red;">86</span> cells<span style="color: green;">&#41;</span>
Main<span style="color: #339933; font-weight: bold;">$</span> fastExprHaskell
<span style="color: red;">17</span>
<span style="color: green;">&#40;</span><span style="color: red;">43</span> reductions<span style="color: #339933; font-weight: bold;">,</span> <span style="color: red;">78</span> cells<span style="color: green;">&#41;</span></pre></div></div>


<p>This is what we expected.</p>

<p>What key lessons can you take from this to use in your everyday Haskell coding?  First, always prefer to create a let outside of a lambda rather than inside of a lambda, to take greater advantage of sharing.  Second, lazy evaluation is not black magic, it doesn&#8217;t evaluate things in an order based off of the phase of the moon; it is deterministic and follows fairly simple semantics.  While tracing impure lazy computations is very difficult, it is not too hard to get a reasonable idea of how a pure lazy function will be evaluated.</p>

<p>(The answers to the questions posed earlier are that the first expression halts because it uses itself before it has been rebound on the heap, the second expression is an infinite loop, and the third one is a normal recursive function that will reduce to the correct answer.)</p>
]]></content:encoded>
			<wfw:commentRss>http://netsuperbrain.com/blog/posts/haskells-evaluation-isnt-magic/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Semantic Editor Combinators - one of my favorite blog posts</title>
		<link>http://netsuperbrain.com/blog/posts/semantic-editor-combiners/</link>
		<comments>http://netsuperbrain.com/blog/posts/semantic-editor-combiners/#comments</comments>
		<pubDate>Tue, 19 Jan 2010 02:54:25 +0000</pubDate>
		<dc:creator>David Sankel</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://netsuperbrain.com/blog/?p=363</guid>
		<description><![CDATA[I wanted to squeeze this blog post into my Best Haskell Papers of 2009 article, but it unfortunately was written in late 2008. For your enjoyment, here is the entry below.


Semantic Editor Combinators - Conal Elliott [link]

Strictly speaking this isn&#8217;t a paper. On the other hand, the functional pearl therein is a must for any [...]]]></description>
			<content:encoded><![CDATA[<p>I wanted to squeeze this blog post into my <a href="http://netsuperbrain.com/blog/posts/best-haskell-papers-of-2009/">Best Haskell Papers of 2009</a> article, but it unfortunately was written in late 2008. For your enjoyment, here is the entry below.
<span id="more-363"></span></p>

<h2>Semantic Editor Combinators - Conal Elliott [<a href="http://conal.net/blog/posts/semantic-editor-combinators/">link</a>]</h2>

<p>Strictly speaking this isn&#8217;t a paper. On the other hand, the functional pearl therein is a must for any Haskeller&#8217;s box of tools. The essence of the presented technique allows one to write easy to understand transforms of functions, or function like things. For example:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">f <span style="color: #339933; font-weight: bold;">::</span> <span style="color: #cccc00; font-weight: bold;">Int</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#40;</span><span style="color: #cccc00; font-weight: bold;">Int</span><span style="color: #339933; font-weight: bold;">,</span><span style="color: #cccc00; font-weight: bold;">Char</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">String</span>
<span style="color: #5d478b; font-style: italic;">-- Want to convert into type g . . .</span>
g <span style="color: #339933; font-weight: bold;">::</span> <span style="color: #cccc00; font-weight: bold;">Int</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#40;</span><span style="color: #cccc00; font-weight: bold;">Int</span><span style="color: #339933; font-weight: bold;">,</span><span style="color: #cccc00; font-weight: bold;">Int</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">String</span>
<span style="color: #5d478b; font-style: italic;">-- with transformer z.</span>
z <span style="color: #339933; font-weight: bold;">::</span> <span style="color: #cccc00; font-weight: bold;">Int</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">Char</span>
<span style="color: #5d478b; font-style: italic;">-- Implementation using semantic editor combinators:</span>
g <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span>result <span style="color: #339933; font-weight: bold;">.</span> argument <span style="color: #339933; font-weight: bold;">.</span> second<span style="color: green;">&#41;</span> z f</pre></div></div>


<p>The g implementation can be read backwards as &#8220;apply the z transformation to the second element of the tuple of the argument of the result of f&#8221;. Recall that functions only have one argument and one result and that the result of a curried function is another function.</p>

<p>It takes a bit of getting used to, but it is definitely worth the investment in time learning. It frequently makes code more elegant and concise.</p>

<p>Note, if you ever get stumbled by an (fmap.fmap.fmap) in code, this is where to go.</p>
]]></content:encoded>
			<wfw:commentRss>http://netsuperbrain.com/blog/posts/semantic-editor-combiners/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Best Haskell Papers of 2009</title>
		<link>http://netsuperbrain.com/blog/posts/best-haskell-papers-of-2009/</link>
		<comments>http://netsuperbrain.com/blog/posts/best-haskell-papers-of-2009/#comments</comments>
		<pubDate>Tue, 19 Jan 2010 02:49:16 +0000</pubDate>
		<dc:creator>David Sankel</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://netsuperbrain.com/blog/?p=318</guid>
		<description><![CDATA[As the year closed I reminisced on all the Haskell related papers I read in 2009.
Some of them lifted my understanding to exciting new heights, while some others seemed impractical or overly tedious. The thought came upon me to present a list of the best of the best with the hope that
these excellent papers might [...]]]></description>
			<content:encoded><![CDATA[<p>As the year closed I reminisced on all the Haskell related papers I read in 2009.
Some of them lifted my understanding to exciting new heights, while some others seemed impractical or overly tedious. The thought came upon me to present a list of the best of the best with the hope that
these excellent papers might inspire and motivate others as they have me.<span id="more-318"></span></p>

<p>Naturally, many will reject such a subjective list. I concede that the list is heavily influenced by my own interests and lack of prerequisite knowledge in some cases. However, I&#8217;d argue that it isn&#8217;t entirely useless.
First, I&#8217;d expect several of these papers to be well respected by experts in their respective fields. In this way, my list does
shadow the objective truth. Second, my rare occupation as a
commercial Haskell contractor makes my personal viewpoints
of particular interest.</p>

<p>So, without further ado, the list.</p>

<h1>The List</h1>

<h2>#7 Experience Report: Haskell in the &#8220;Real World&#8221; - Curt J. Sampson [<a href="http://portal.acm.org/citation.cfm?id=1596550.1596578">abstract</a>][<a href="http://www.starling-software.com/misc/icfp-2009-cjs.pdf">pdf</a>]</h2>

<p>This paper showcases the decision of a software business to use functional programming without any prior experience with the paradigm. The business&#8217;s choice of Haskell for a programming language was outlined as well as the benefits they enjoyed. What struck me in particular were the <em>problems and disadvantages</em> the programming team encountered. It was refreshing to see my own experiences with these issues put so clearly. I point business associates primarily to this paper for an introduction to using Haskell commercially.</p>

<h2>#6 Algebra of programming in Agda: Dependent types for relational program derivation - Shin-Cheng Mu et al.[<a href="http://journals.cambridge.org/action/displayAbstract?aid=6171388">abstract</a>][<a href="http://www.iis.sinica.edu.tw/~scm/pub/aopa.pdf">pdf</a>]</h2>

<p>Agda, a dependently typed programming language with a syntax similar to Haskell, is fueling a lot of research this year. After reading many papers such as this one, I can&#8217;t help but think that the future lies in dependent types.</p>

<p>This paper presents an unorthodox approach to writing programs called relational program derivation. One starts by encoding a proposition, for example &#8220;the algorithm x sorts all lists&#8221;, and then <em>deriving</em> a program that the proposition is true for, like quicksort. The authors created an algebra for encoding these derivations in Agda. By using Agda, the derived programs include a computer verified proof of correctness.</p>

<p>I think it is going to take a while before the programming community, myself included, becomes fully aware of the implications of this paper.</p>

<h2>#5 Fun with Type Functions - Oleg Kiselyov, Simon Peyton Jones, Chung-chieh Shan [<a href="http://haskell.org/haskellwiki/Simonpj/Talk:FunWithTypeFuns">link</a>][<a href="http://research.microsoft.com/~simonpj/papers/assoc-types/fun-with-type-funs/typefun.pdf">pdf</a>]</h2>

<p>Reaching a limitation of the type checker is a common cause of ire for Haskell programmers. Type families, a new feature of ghc, removes a sizable amount of these limitations. Superseding an earlier compiler extension, functional dependencies, type families opens up many new areas of generic programming as well. One of the most interesting examples from the paper is a <em>simple</em> type-safe implementation of printf and scanf.</p>

<p>Note that the final version of this paper has not been published yet.</p>

<h2>#4 Commercial uses: Going functional on exotic trades - Simon Frankau et al.[<a href="http://journals.cambridge.org/action/displayAbstract?aid=2837484">abstract</a>][<a href="http://www.lexifi.com/downloads/frankau.pdf">pdf</a>]</h2>

<p>Where the #7 spot paper expounds on the implications of switching to Haskell, this paper gives an in depth detail of a commercial domain specific embedded language (DSEL) using Haskell. The explanations  within were atypically clear and well referenced. After studying this paper I felt confidant in using Haskell as a host language for DSEL&#8217;s.</p>

<p>For someone new to DSEL&#8217;s, this paper is great first read. In my opinion, DSEL&#8217;s are one of the most lucrative uses of Haskell commercially.</p>

<h2>#3 Safe Functional Reactive Programming through Dependent types - Neil Sculthorpe, Henrik Nilsson [<a href="http://portal.acm.org/citation.cfm?id=1631687.1596558">abstract</a>][<a href="http://www.cs.nott.ac.uk/~nas/papers_and_talks/icfp09.pdf">pdf</a>]</h2>

<p>This paper contributed two important findings to the field of functional reactive programming (FRP). First, it presented several obvious defects in current FRP implementations. Those who&#8217;ve programed with FRP in any depth are painfully aware of how easy it is to accidentally create programs that loop or leak memory at run-time. Sculthorpe and Nilsson pinpoint the exact cause of these issues.</p>

<p>The second major contribution is an FRP implementation that they proved does not have these problems. The aforementioned proof is computer verified. Can you guess how they did it? If you guessed that they used Agda, you&#8217;d be right! Amazing stuff.</p>

<h2>#2 Typeclassopedia  - Brent Yorgey [<a href="http://haskell.org/sitewiki/images/8/85/TMR-Issue13.pdf">pdf</a>]</h2>

<p>Brent Yorgey&#8217;s Typeclassopedia, published in the <a href="http://themonadreader.wordpress.com/">Monad.Reader</a> is the most comprehensive tutorial on the basic Haskell type classes (like Monoids, Monads, etc.) thus far. It stands out in both its accessibility to all levels of Haskell developers and its vast coverage. The paper can be used both as a tutorial and a reference. For more in-depth studies, lots of useful references are also included.</p>

<p>This paper is a great contribution to the Haskell community and will surely become a classic.</p>

<h2>#1 Finally Tagless, Partially Evaluated - Jacques Carette, Oleg Kiselyov and Chung-Chieh Shan [<a href="http://journals.cambridge.org/action/displayAbstract?aid=6171376">abstract</a>][<a href="http://www.cs.rutgers.edu/~ccshan/tagless/jfp.pdf">pdf</a>]</h2>

<p>The essence of this paper is so simple, it bears repeating right here</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">varZ env <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">fst</span> env
varS vp env <span style="color: #339933; font-weight: bold;">=</span> vp <span style="color: #339933; font-weight: bold;">$</span> <span style="font-weight: bold;">snd</span> env
b b env <span style="color: #339933; font-weight: bold;">=</span> b
lam a env <span style="color: #339933; font-weight: bold;">=</span> \x <span style="color: #339933; font-weight: bold;">-&gt;</span> a <span style="color: green;">&#40;</span>x<span style="color: #339933; font-weight: bold;">,</span>env<span style="color: green;">&#41;</span>
app a b env <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span>a env<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>b env<span style="color: green;">&#41;</span></pre></div></div>


<p>What you&#8217;re looking at is a simple implementation of a <em>typed</em> embedded language using Haskell98 as a host for both the language <em>and</em> the type checking. Prior to this paper, embedded language designers took advantage of Haskell98&#8217;s syntax, but not its type system.</p>

<p>The problem the authors so elegantly solve using Haskell98 was a main motivation behind the complex generalized algebraic data type (GADT) extensions to Haskell. Perhaps this extension isn&#8217;t necessary after all.</p>

<p>They further describe how to extend this simple interpreter to various efficient compilers and interpreters without modification of the original embedded language. Although the paper primarily uses OCaml, they provide equivalent Haskell code on their website.</p>

<p>I&#8217;m looking forward to seeing more complex embedded languages built on the ideas of this paper. It wins first prize for elegance, utility, and cleverness.</p>

<h1>Notes</h1>

<h2>Runner-ups</h2>

<p><strong>The Arrow Calculus (Technical Report) - Sam Lindley, Philip Wadler, and Jeremy Yallop</strong> [<a href="http://groups.inf.ed.ac.uk/links/arrows/">link</a>]. This paper describes a new syntax for arrows that more closely resembles the lambda calculus. It remains to be seen if this syntax is easier to use than our current proc syntax.</p>

<p><strong>Push-pull functional reactive programming - Conal Elliott</strong> [<a href="Push-pull functional reactive programming">link</a>]. This paper is a theoretically elegant refactoring of FRP using standard type classes. Had I not directly encountered the subtle, and serious, bugs of this implementation in a commercial setting, it probably would have made the list.</p>

<p><strong>Denotational Semantics - David Schmidt</strong> [<a href="http://people.cis.ksu.edu/~schmidt/text/densem.html">link</a>]. This is a book written in 1982 that I read last year. It is just as relevant today as it was back then. An excellent exposition of denotational semantics. My programming has substantially changed for the better since that read. It was regretfully disqualified for the medium and date of publication.</p>

<h2>Where I hear about these papers</h2>

<p><strong><a href="http://journals.cambridge.org/action/displayJournal?jid=JFP">Journal of Functional Programming</a></strong>. I purchased a paper subscription.</p>

<p><strong><a href="http://themonadreader.wordpress.com/">The Monad.Reader</a></strong>. A must-read, freely available Haskell journal.</p>

<p><strong><a href="http://sequence.complete.org/hwn">Haskell Weekly News</a></strong>. A weekly summary of community activity. A great place to discover powerful blog posts or pre-releases of journal articles.</p>

<p><strong>Proceedings of <a href="http://www.icfpconference.org/">ICFP</a> (International Conference of Functional Programming) and affiliated SIGPLANs</strong>. I have access to these from the ACM website because I&#8217;m an alumnus of the University of Rochester. It took me a long time to get through the great quantity of papers available here, but it was very worthwhile.</p>

<h2>Apology</h2>

<p>I apologize for all mistakes and especially all my omissions. I am certain there are papers that would have made the list had I only read or understood them. I invite my readers to point out their favorites in the comments below.</p>

<p>Thanks to all who contribute to this field and give me countless hours of enjoyable reading and pondering.</p>

<p>See <a href="http://netsuperbrain.com/blog/posts/semantic-editor-combiners/">a short note</a> on a blog post that I really wanted to be on this list.</p>
]]></content:encoded>
			<wfw:commentRss>http://netsuperbrain.com/blog/posts/best-haskell-papers-of-2009/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Applied Functional Programming: Part 1</title>
		<link>http://netsuperbrain.com/blog/posts/applied-functional-programming-part-1/</link>
		<comments>http://netsuperbrain.com/blog/posts/applied-functional-programming-part-1/#comments</comments>
		<pubDate>Mon, 14 Sep 2009 17:02:40 +0000</pubDate>
		<dc:creator>David Sankel</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://netsuperbrain.com/blog/?p=290</guid>
		<description><![CDATA[This post begins a two part series designed to present functional programming concepts as they apply to real world programming. Using functional techniques, we&#8217;ll solve a problem that came up in a commercial project I&#8217;m working on.


I&#8217;m a seasoned freelance software developer. There&#8217;s no PhD after my name and I&#8217;ve written heaps of C++ and [...]]]></description>
			<content:encoded><![CDATA[<p>This post begins a two part series designed to present functional programming concepts as they apply to real world programming. Using functional techniques, we&#8217;ll solve a problem that came up in a commercial project I&#8217;m working on.
<span id="more-290"></span></p>

<p>I&#8217;m a seasoned freelance software developer. There&#8217;s no PhD after my name and I&#8217;ve written heaps of C++ and python code for commercial projects. For me, concepts need to be both practical and time-saving before I integrate them into my development work. On the other hand, I enjoy thinking about and studying concepts that are thought provoking and clever, like <a href="http://portal.acm.org/citation.cfm?id=1520289">first class patterns in pure pattern calculus</a> for example.</p>

<p>My focus, for these posts, is where these two categories merge. Maybe we can call this fuzzy area applied theory. All too often, applied theory isn&#8217;t taught or written about and doesn&#8217;t reach Joe the programmer who can actually use it on his project.</p>

<p>After reading interesting research papers, I often ask myself one or both of two questions: &#8220;What problems, that I&#8217;ve encountered or might encounter, would I want to solve with this?&#8221;, and &#8220;What are the details required to put this to use?&#8221;. Working out the answers to these questions is a real joy for me. I don&#8217;t always figure out how to make clever ideas useful or practical, but when I do, and subsequently use it in a commercial project, I get a lot of satisfaction.</p>

<p>Lets see what techniques we can apply to a giant, ugly heap of poo code that I&#8217;ve been working with. You&#8217;ll recognize it as the code base that combines an intense security requirement with occasional embarrassing vulnerabilities. <a href="http://openssl.org">OpenSSL</a> is the name.</p>

<p>Now, I want to make it clear that I&#8217;m not dissing the OpenSSL developers (except maybe <a href="https://www.openssl.org/source/license.html">Eric Young</a> for including a self-advertising clause in the license that still sticks to this day). I&#8217;ve written my share of what I call &#8220;superman code&#8221;.</p>

<p>How does superman code arise? You get a call from a frantic customer: &#8220;Hey, we need to write X software and we need it in 2 days&#8221;. You put on your cape and fly out there immediately. With plenty of caffeine and snacks, you hack together something with super-human speed that solves their imminent problem. You fly back home tired and they throw a party while crediting you (or themselves occasionally) for being a genius. 6 months later you revisit the superman code and scratch your head wondering just what the heck did the undocumented X509_REVOKED_add1_ext_i2d function do again? You end up rewriting half of it.</p>

<p>Our example is an OpenSSL function called <a href="http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html">SSL_CTX_set_verify</a>. Give that manpage a quick read to get a idea what that function does. My task was to make a preexisting OpenSSL client verify that the server&#8217;s certificate was valid upon connection. The code below shows the lines of code I added:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">asio<span style="color: #339933; font-weight: bold;">::</span>ssl<span style="color: #339933; font-weight: bold;">::</span>context context<span style="color: green;">&#40;</span> io<span style="color: #339933; font-weight: bold;">_</span>service
                          <span style="color: #339933; font-weight: bold;">,</span> asio<span style="color: #339933; font-weight: bold;">::</span>ssl<span style="color: #339933; font-weight: bold;">::</span>context<span style="color: #339933; font-weight: bold;">::</span>tlsv1<span style="color: #339933; font-weight: bold;">_</span>client
                          <span style="color: green;">&#41;</span>;
<span style="color: #339933; font-weight: bold;">//</span><span style="color: red;">2</span> New Lines
context<span style="color: #339933; font-weight: bold;">.</span>set<span style="color: #339933; font-weight: bold;">_</span>verify<span style="color: #339933; font-weight: bold;">_</span>mode<span style="color: green;">&#40;</span>asio<span style="color: #339933; font-weight: bold;">::</span>ssl<span style="color: #339933; font-weight: bold;">::</span>context<span style="color: #339933; font-weight: bold;">::</span>verify<span style="color: #339933; font-weight: bold;">_</span>peer<span style="color: green;">&#41;</span>;
context<span style="color: #339933; font-weight: bold;">.</span>load<span style="color: #339933; font-weight: bold;">_</span>verify<span style="color: #339933; font-weight: bold;">_</span>file<span style="color: green;">&#40;</span><span style="background-color: #3cb371;">&quot;ca.pem&quot;</span><span style="color: green;">&#41;</span>;
<span style="color: #339933; font-weight: bold;">//...</span></pre></div></div>


<p>Note that I&#8217;m using the <a href="http://www.boost.org/doc/libs/1_37_0/doc/html/boost_asio.html">boost.asio</a> library which includes a thin wrapper on OpenSSL. Unfortunately, my small change didn&#8217;t work when I ran it. Can you spot the bug?</p>

<p>I hope you didn&#8217;t spend as much time as I did looking for a bug in either the boost.asio or OpenSSL code bases. My bug was in the &#8220;//&#8230;&#8221; part. Lets expand a little bit:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">asio<span style="color: #339933; font-weight: bold;">::</span>ssl<span style="color: #339933; font-weight: bold;">::</span>context context<span style="color: green;">&#40;</span> io<span style="color: #339933; font-weight: bold;">_</span>service
                          <span style="color: #339933; font-weight: bold;">,</span> asio<span style="color: #339933; font-weight: bold;">::</span>ssl<span style="color: #339933; font-weight: bold;">::</span>context<span style="color: #339933; font-weight: bold;">::</span>tlsv1<span style="color: #339933; font-weight: bold;">_</span>client
                          <span style="color: green;">&#41;</span>;
<span style="color: #339933; font-weight: bold;">//</span><span style="color: red;">2</span> New Lines
context<span style="color: #339933; font-weight: bold;">.</span>set<span style="color: #339933; font-weight: bold;">_</span>verify<span style="color: #339933; font-weight: bold;">_</span>mode<span style="color: green;">&#40;</span>asio<span style="color: #339933; font-weight: bold;">::</span>ssl<span style="color: #339933; font-weight: bold;">::</span>context<span style="color: #339933; font-weight: bold;">::</span>verify<span style="color: #339933; font-weight: bold;">_</span>peer<span style="color: green;">&#41;</span>;
context<span style="color: #339933; font-weight: bold;">.</span>load<span style="color: #339933; font-weight: bold;">_</span>verify<span style="color: #339933; font-weight: bold;">_</span>file<span style="color: green;">&#40;</span><span style="background-color: #3cb371;">&quot;ca.pem&quot;</span><span style="color: green;">&#41;</span>;
<span style="color: #339933; font-weight: bold;">//...</span>
context<span style="color: #339933; font-weight: bold;">.</span>set<span style="color: #339933; font-weight: bold;">_</span>verify<span style="color: #339933; font-weight: bold;">_</span>mode<span style="color: green;">&#40;</span>asio<span style="color: #339933; font-weight: bold;">::</span>ssl<span style="color: #339933; font-weight: bold;">::</span>context<span style="color: #339933; font-weight: bold;">::</span>verify<span style="color: #339933; font-weight: bold;">_</span>none<span style="color: green;">&#41;</span>;
<span style="color: #339933; font-weight: bold;">//...</span></pre></div></div>


<p>Oops! I changed the verify mode twice. What a bummer! This is where a functional programming principle, called purity, comes into play.</p>

<p>&#8220;set_verify_mode&#8221; is really a misnomer because what we are actually doing is <em>changing</em> the verify mode &#8220;state&#8221; to something else. The type of that function, in Haskell notation, would be something like:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">set<span style="color: #339933; font-weight: bold;">_</span>verify<span style="color: #339933; font-weight: bold;">_</span>mode <span style="color: #339933; font-weight: bold;">::</span> Context <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">Int</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> Context</pre></div></div>


<p>We can do better. What we really want to do is define a context with a specified verify mode [declarative style], not create an arbitrary default context and change it [imperative style].</p>

<p>Consider the following code:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">data</span> ContextParams <span style="color: #339933; font-weight: bold;">=</span> CP <span style="color: green;">&#123;</span> verifyMode <span style="color: #339933; font-weight: bold;">::</span> <span style="color: #cccc00; font-weight: bold;">Int</span>
                        <span style="color: #5d478b; font-style: italic;">-- ...</span>
                        <span style="color: green;">&#125;</span>
context <span style="color: #339933; font-weight: bold;">::</span> ContextParams <span style="color: #339933; font-weight: bold;">-&gt;</span> Context</pre></div></div>


<p>What we&#8217;re doing is moving all the imperative set_ functions (that really modify a context) into the &#8220;constructor&#8221; of Context. This being the case, we&#8217;re disallowing, at compile time, the changing of the context verify mode. The bug I introduced would never have made it to run time if Context was designed in this way.</p>

<p>Moving on, lets see if we can stop passing Ints around. I want to disallow the following type of code from compiling:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">let</span> c <span style="color: #339933; font-weight: bold;">=</span> context <span style="color: #339933; font-weight: bold;">$</span> CP <span style="color: green;">&#123;</span> verifyMode <span style="color: #339933; font-weight: bold;">=</span> <span style="color: red;">3</span> <span style="color: #339933; font-weight: bold;">+</span> <span style="color: red;">22</span>
                     <span style="color: #339933; font-weight: bold;">,</span> <span style="color: #5d478b; font-style: italic;">--...</span>
                     <span style="color: green;">&#125;</span></pre></div></div>


<p>Setting a verifyMode to a sum of numbers really doesn&#8217;t make sense, does it? The essence of the verify mode is not an Integer, but something else. Looking at the <a href="http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html">manual page</a>, we see that there are different sets of verify modes that make sense depending whether or not the context is a client or server. That indicates to me two distinct data types.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">data</span> ClientVerifyMode <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #5d478b; font-style: italic;">-- ...</span>
<span style="color: #06c; font-weight: bold;">data</span> ServerVerifyMode <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #5d478b; font-style: italic;">-- ...</span></pre></div></div>


<p>Lets set up a simple client mode definition:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">data</span> ClientVerifyMode <span style="color: #339933; font-weight: bold;">=</span> ClientVerifyPeer
                      | ClientVerifyNone</pre></div></div>


<p>But going further, we know that if we&#8217;re verifying the peer we&#8217;ll be needing certificate authority keys to verify with (this is set with the <a href="http://www.openssl.org/docs/ssl/SSL_CTX_use_certificate.html">SSL_CTX_use_certificate_file</a> function). Also required would be the maximum certificate depth (<a href="http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html">SSL_CTX_set_verify_depth</a>). On the other hand the SSL_CTX_set_verify function allows for a function to be passed to override the other parameters. Further &#8220;out there&#8221;, one could bypass all this stuff by writing his own verification function with <a href="http://www.openssl.org/docs/ssl/SSL_CTX_set_cert_verify_callback.html">SSL_CTX_set_cert_verify_callback</a>.</p>

<p>Confusing? I found it confusing anyway. How can we simplify this? What is the <em>essence </em> of what we are trying to do here? The answer can be found by acting like a buddhist monk. Go take an unstructured walk. Exhale your desires and aversions. Inhale nature. Feel the oneness of all things. Notice the feeling of being touched by your clothing or the taste in your mouth. This is living. This is the field of inspiration. This is where the answer lies if it falls upon the path of your destiny.</p>

<p>Welcome back. What our function and its relatives boils down to is verification of the peer&#8217;s credentials, which is a certificate chain. Either the credentials are acceptable or they are not by whatever means you check them. So, the <em>essence</em> we&#8217;ve been looking for is:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">data</span> ClientPeerVerifier <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #5d478b; font-style: italic;">-- Credentials -&gt; Bool</span></pre></div></div>


<p>That little comment is there to document our intended semantics or meaning. We derived this while doing hippie things. I plan on talking more about meanings and the subject of denotational semantics in a later post. Now we can give appropriate names to the specializations available in OpenSSL</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">data</span> ClientPeerVerifier <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #5d478b; font-style: italic;">-- Credentials -&gt; Bool</span>
                        | F <span style="color: green;">&#40;</span>Credentials<span style="color: #339933; font-weight: bold;">-&gt;</span>Bool<span style="color: green;">&#41;</span></pre></div></div>


<p>The F constructor, standing for function, represents the most general <a href="http://www.openssl.org/docs/ssl/SSL_CTX_set_cert_verify_callback.html">SSL_CTX_set_cert_verify_callback</a> style verifier. Now some more</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">data</span> ClientPeerVerifier <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #5d478b; font-style: italic;">-- Credentials -&gt; Bool</span>
                        | F <span style="color: green;">&#40;</span>Credentials<span style="color: #339933; font-weight: bold;">-&gt;</span>Bool<span style="color: green;">&#41;</span>
                        | ConstTrue
                        | SimpleVerify TrustedCertificates <span style="color: #cccc00; font-weight: bold;">Int</span></pre></div></div>


<p>ConstTrue will represent the SSL_VERIFY_NONE parameter. Notice how our semantics imply a nice name for this (&#8221;const True&#8221; is a function that returns True for every input). SimpleVerify merges <a href="http://www.openssl.org/docs/ssl/SSL_CTX_use_certificate.html">SSL_CTX_use_certificate_file</a>, <a href="http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html">SSL_CTX_set_verify_depth</a>, and <a href="http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html">SSL_VERIFY_PEER</a>.</p>

<p>There is something missing still, what about that &#8220;further verification process&#8221; controlled by the verify_callback parameter of the SSL_CTX_set_verify function? If we tried to implement this in our semantics, and call it z, we&#8217;d have:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">z <span style="color: #339933; font-weight: bold;">::</span> TrustedCertificates <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">Int</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#40;</span>Credentials <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">Bool</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">Bool</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#40;</span>Credentials <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">Bool</span><span style="color: green;">&#41;</span>
z ts depth g c <span style="color: #339933; font-weight: bold;">=</span> g <span style="color: green;">&#40;</span>simpleVerify ts depth c<span style="color: green;">&#41;</span> c</pre></div></div>


<p>The first two parameters are the same as SimpleVerify above. The third parameter is a function taking in credentials and the result of the simple verify procedure.</p>

<p>Lacking a good name for Z, lets call it verifyWithSimpleVerifyResult. SimpleVerify is really a specialization of this, but we&#8217;ll leave it in case there is some optimization for a NULL verify_func argument to SSL_CTX_set_verify.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">data</span> ClientPeerVerifier <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #5d478b; font-style: italic;">-- Credentials -&gt; Bool</span>
                        | F <span style="color: green;">&#40;</span>Credentials<span style="color: #339933; font-weight: bold;">-&gt;</span>Bool<span style="color: green;">&#41;</span>
                        | ConstTrue
                        | SimpleVerify TrustedCertificates <span style="color: #cccc00; font-weight: bold;">Int</span>
                        | VerifyWithSimpleVerifyResult TrustedCertificates <span style="color: #cccc00; font-weight: bold;">Int</span> <span style="color: green;">&#40;</span>Credentials <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">Bool</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">Bool</span><span style="color: green;">&#41;</span></pre></div></div>


<p>Now we have all our cases covered. The only thing I might add to the code would be a comment explaining the meaning of VerifyWithSimpleVerifyResult, for example the definition of z above.</p>

<p>We could, if we wanted, write functions that have a user description (as opposed to semantic name) to help a user document his own code:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">alwaysAccept <span style="color: #339933; font-weight: bold;">::</span> ClientPeerVerifier
alwaysAccept <span style="color: #339933; font-weight: bold;">=</span> ConstTrue</pre></div></div>


<p>For the ServerPeerVerifier, we&#8217;ll need a different meaning, or essence, as a client doesn&#8217;t always supply a certificate.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">data</span> ServerPeerVerifier <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #5d478b; font-style: italic;">-- Maybe Credentials -&gt; Bool</span></pre></div></div>


<h2>Concluding Thoughts</h2>

<p>Using semantics, in many ways, obviates the need for a large portion of documentation. For example, knowing the semantics of ClientPeerVerifier allows me to understand completely ConstTrue by only reading its name. Compare this approach to the wordy, and incomplete, manual pages of OpenSSL. Thinking in semantics has a whole lot of other advantages as well which I&#8217;ll cover in another post.</p>

<p>Judiciously using purity and specialized data types (like we did when removing the use of Int for verifyMode) assists a developer in writing bug-free programs by disallowing a slew of bugs to get past the compilation stage.</p>

<p>For the actual project, I would likely continue using C++ but make the data types match what they would be if I were to transfer the Haskell code above. It turns out this isn&#8217;t as hard as one might think. The real use of Haskell on this problem was to construct a framework to understand the code that was there and design a new meaningful wrapper.</p>

<h2>Excercises</h2>

<p>Feel free to post your answers as comments.</p>

<p>(*) Figure out what to call the SSL_VERIFY_FAIL_IF_NO_PEER_CERT style ServerPeerVerifier.</p>

<p>(*) How would the semantics (meanings) need to change if we were handling the SSL_VERIFY_CLIENT_ONCE parameter?</p>

<p>(**) The <a href="http://www.openssl.org/docs/ssl/SSL_CTX_set_cert_verify_callback.html">SSL_CTX_set_cert_verify_callback</a> function actually expects the callback to modify one of its arguments. If we wanted to include this functionality, how would we change the return value our ClientPeerVerifier semantics?</p>

<p>(**) Using the meaning style presented above or another functional style, write an OpenSSL wrapper in Haskell and submit it to Hackage. (Thanks!)</p>
]]></content:encoded>
			<wfw:commentRss>http://netsuperbrain.com/blog/posts/applied-functional-programming-part-1/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Synchronous Events</title>
		<link>http://netsuperbrain.com/blog/posts/synchronous-events/</link>
		<comments>http://netsuperbrain.com/blog/posts/synchronous-events/#comments</comments>
		<pubDate>Wed, 10 Dec 2008 15:57:03 +0000</pubDate>
		<dc:creator>David Sankel</dc:creator>
		
		<category><![CDATA[Haskell]]></category>

		<guid isPermaLink="false">http://netsuperbrain.com/blog/?p=261</guid>
		<description><![CDATA[It turns out that there&#8217;s a certain class of event transformers (Event a -> Event b) in Reactive that have some really neat and convenient properties. We&#8217;ll call this class synchronous event transformers.


The event transformers we&#8217;re interested in ( : Event a -> Event b) semantically have the following property.



where


pfst = map fst


In other words, [...]]]></description>
			<content:encoded><![CDATA[<p>It turns out that there&#8217;s a certain class of event transformers (Event a -> Event b) in Reactive that have some really neat and convenient properties. We&#8217;ll call this class synchronous event transformers.
<span id="more-261"></span></p>

<p>The event transformers we&#8217;re interested in (<img src="http://netsuperbrain.com/blog/wp-content/cache/tex_8fa14cdd754f91cc6554c9e71929cce7.png" align="absmiddle" class="tex" alt="f" /> : Event a -> Event b) semantically have the following property.</p>

<p><center><img src="http://netsuperbrain.com/blog/wp-content/cache/tex_a93608a15c72e1cfba007f488ab01782.png" align="absmiddle" class="tex" alt=" \forall e \in \text{Event } a, \text{pfst }(f e) == \text{pfst }e" /></center></p>

<p>where</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">pfst <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">map</span> <span style="font-weight: bold;">fst</span></pre></div></div>


<p>In other words, synchronous event transformers do not change the number of occurrences nor the times of occurrences of the argument. Most of Reactive&#8217;s event transformers have this property. Lets make a simple wrapper for Synchronous transformers:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">type</span> EventT a b <span style="color: #339933; font-weight: bold;">=</span> Event a <span style="color: #339933; font-weight: bold;">-&gt;</span> Event b
<span style="color: #06c; font-weight: bold;">newtype</span> Synchronous a b <span style="color: #339933; font-weight: bold;">=</span> S <span style="color: green;">&#123;</span>toEventT <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#40;</span>EventT a b<span style="color: green;">&#41;</span><span style="color: green;">&#125;</span></pre></div></div>


<p>There may be a better representation. Conal Elliott on #haskell suggested using <a href="http://conal.net/blog/posts/functional-reactive-chatter-bots/">MutantBots</a>, but they aren&#8217;t expressive enough to encapsulate transformers like <code>withNextE</code>. For the purpose of this discussion, we&#8217;ll use the above representation and invite the reader to come up with a better one.</p>

<p>Some helper functions will come in handy. By the way, we&#8217;ll be using the style of <a href="http://conal.net/blog/posts/semantic-editor-combinators/">Semantic Editor Combinators</a>.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">inS <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>EventT a b<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#40;</span>EventT c d<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#40;</span>Synchronous a b <span style="color: #339933; font-weight: bold;">-&gt;</span> Synchronous c d<span style="color: green;">&#41;</span>
inS f <span style="color: #339933; font-weight: bold;">=</span>  S <span style="color: #339933; font-weight: bold;">.</span> f <span style="color: #339933; font-weight: bold;">.</span> toEventT
&nbsp;
inS2 <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>EventT a b<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#40;</span>EventT c d<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#40;</span>EventT e f<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span>
        <span style="color: green;">&#40;</span>Synchronous a b <span style="color: #339933; font-weight: bold;">-&gt;</span> Synchronous c d <span style="color: #339933; font-weight: bold;">-&gt;</span> Synchronous e f<span style="color: green;">&#41;</span>
inS2 f <span style="color: green;">&#40;</span>S a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>S b<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> S <span style="color: green;">&#40;</span>f a b<span style="color: green;">&#41;</span></pre></div></div>


<p>An easy thing to see is that our Synchronous Event Transformers (SET&#8217;s) are Functors. The definition of fmap simply applies the function to the resultant event.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">instance</span> <span style="color: #cccc00; font-weight: bold;">Functor</span> <span style="color: green;">&#40;</span>Synchronous a<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <span style="font-weight: bold;">fmap</span> <span style="color: #339933; font-weight: bold;">=</span> inS <span style="color: #339933; font-weight: bold;">.</span> <span style="font-weight: bold;">fmap</span> <span style="color: #339933; font-weight: bold;">.</span> <span style="font-weight: bold;">fmap</span></pre></div></div>


<p>One interesting thing about synchronous events is that we can apply one to another in parallel. In other words, if we have an event of functions and an event of values, we can apply each function event to each value event if they are synchronous.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #5d478b; font-style: italic;">-- Only works on events that are synchronous</span>
apSync <span style="color: #339933; font-weight: bold;">::</span>  EventG t <span style="color: green;">&#40;</span>a<span style="color: #339933; font-weight: bold;">-&gt;</span>b<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> EventG t a <span style="color: #339933; font-weight: bold;">-&gt;</span> EventG t b
apSync <span style="color: #339933; font-weight: bold;">=</span> inEvent2 f
  <span style="color: #06c; font-weight: bold;">where</span>
    f <span style="color: #339933; font-weight: bold;">=</span> inFuture2 <span style="color: green;">&#40;</span>\<span style="color: green;">&#40;</span>ta<span style="color: #339933; font-weight: bold;">,</span>a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">_,</span> b<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#40;</span>ta<span style="color: #339933; font-weight: bold;">,</span> g a b<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
    g <span style="color: green;">&#40;</span>Stepper a ae<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>Stepper b be<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span>Stepper <span style="color: green;">&#40;</span>a b<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>apSync ae be<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre></div></div>


<p>If we have two synchronous event transformers, how can we combine them? One way would be to use apSync on their results:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">apSyncT <span style="color: #339933; font-weight: bold;">::</span> Synchronous e <span style="color: green;">&#40;</span>d <span style="color: #339933; font-weight: bold;">-&gt;</span> f<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> Synchronous e d <span style="color: #339933; font-weight: bold;">-&gt;</span> Synchronous e f
apSyncT <span style="color: #339933; font-weight: bold;">=</span> inS2 <span style="color: green;">&#40;</span>\f g e <span style="color: #339933; font-weight: bold;">-&gt;</span> apSync <span style="color: green;">&#40;</span>f e<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>g e<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre></div></div>


<p>Hey, that looks mighty familiar:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">instance</span> Applicative <span style="color: green;">&#40;</span>Synchronous a<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  pure <span style="color: #339933; font-weight: bold;">=</span> S <span style="color: #339933; font-weight: bold;">.</span> pure <span style="color: #339933; font-weight: bold;">.</span> pure
  <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">&lt;*&gt;</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> apSyncT</pre></div></div>


<p>Interesting. Now we have an Applicative instance for synchronous event transformers. Later on, we&#8217;ll see how this is useful. As it turns out we can declare Category and Arrow instances as well:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">instance</span> Category Synchronous <span style="color: #06c; font-weight: bold;">where</span>
  <span style="font-weight: bold;">id</span> <span style="color: #339933; font-weight: bold;">=</span> S <span style="font-weight: bold;">id</span>
  <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">.</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> inS2 <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">.</span><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Arrow Synchronous <span style="color: #06c; font-weight: bold;">where</span>
  arr <span style="color: #339933; font-weight: bold;">=</span> S <span style="color: #339933; font-weight: bold;">.</span> <span style="font-weight: bold;">fmap</span>
  <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">&amp;&amp;</span>&amp;<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> liftA2 <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">,</span><span style="color: green;">&#41;</span>
  <span style="color: #5d478b; font-style: italic;">-- Defined in terms of (&amp;&amp;&amp;)</span>
  first f <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span>f <span style="color: #339933; font-weight: bold;">.</span> arr <span style="font-weight: bold;">fst</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">&amp;&amp;</span>&amp; arr <span style="font-weight: bold;">snd</span></pre></div></div>


<p>As with any applicative functor, we can define forwarded Num instances</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #5d478b; font-style: italic;">-- Boilerplate taken from Reactive</span>
noOv <span style="color: #339933; font-weight: bold;">::</span> <span style="color: #cccc00; font-weight: bold;">String</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">String</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> a
noOv ty meth <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">error</span> <span style="color: #339933; font-weight: bold;">$</span> meth <span style="color: #339933; font-weight: bold;">++</span> <span style="background-color: #3cb371;">&quot;: No overloading for &quot;</span> <span style="color: #339933; font-weight: bold;">++</span> ty
&nbsp;
noFun <span style="color: #339933; font-weight: bold;">::</span> <span style="color: #cccc00; font-weight: bold;">String</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> a
noFun <span style="color: #339933; font-weight: bold;">=</span> noOv <span style="background-color: #3cb371;">&quot;behavior&quot;</span>
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- Eq &amp; Show are prerequisites for Num, so they need to be faked here</span>
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: #cccc00; font-weight: bold;">Eq</span> <span style="color: green;">&#40;</span>Synchronous a b<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">==</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> noFun <span style="background-color: #3cb371;">&quot;(==)&quot;</span>
  <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">/=</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> noFun <span style="background-color: #3cb371;">&quot;(/=)&quot;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: #cccc00; font-weight: bold;">Show</span> <span style="color: green;">&#40;</span>Synchronous a b<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <span style="font-weight: bold;">show</span>      <span style="color: #339933; font-weight: bold;">=</span> noFun <span style="background-color: #3cb371;">&quot;show&quot;</span>
  showsPrec <span style="color: #339933; font-weight: bold;">=</span> noFun <span style="background-color: #3cb371;">&quot;showsPrec&quot;</span>
  <span style="font-weight: bold;">showList</span>  <span style="color: #339933; font-weight: bold;">=</span> noFun <span style="background-color: #3cb371;">&quot;showList&quot;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: #cccc00; font-weight: bold;">Num</span> b <span style="color: #339933; font-weight: bold;">=&gt;</span> <span style="color: #cccc00; font-weight: bold;">Num</span> <span style="color: green;">&#40;</span>Synchronous a b<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <span style="font-weight: bold;">negate</span>      <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">fmap</span> <span style="font-weight: bold;">negate</span>
  <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">+</span><span style="color: green;">&#41;</span>         <span style="color: #339933; font-weight: bold;">=</span> liftA2 <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">+</span><span style="color: green;">&#41;</span>
  <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">*</span><span style="color: green;">&#41;</span>         <span style="color: #339933; font-weight: bold;">=</span> liftA2 <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">*</span><span style="color: green;">&#41;</span>
  <span style="font-weight: bold;">fromInteger</span> <span style="color: #339933; font-weight: bold;">=</span> pure <span style="color: #339933; font-weight: bold;">.</span> <span style="font-weight: bold;">fromInteger</span>
  <span style="font-weight: bold;">abs</span>         <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">fmap</span> <span style="font-weight: bold;">abs</span>
  <span style="font-weight: bold;">signum</span>      <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">fmap</span> <span style="font-weight: bold;">signum</span></pre></div></div>


<h1>Uses</h1>

<p>Now that we have all these properties of synchronous events, how can we use them? Lets consider the types of a couple functions in reactive</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">withTimeE <span style="color: #339933; font-weight: bold;">::</span> <span style="color: #cccc00; font-weight: bold;">Ord</span> t <span style="color: #339933; font-weight: bold;">=&gt;</span> EventG <span style="color: green;">&#40;</span>Improving t<span style="color: green;">&#41;</span> d <span style="color: #339933; font-weight: bold;">-&gt;</span> EventG <span style="color: green;">&#40;</span>Improving t<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>d<span style="color: #339933; font-weight: bold;">,</span> t<span style="color: green;">&#41;</span>
withTimeE<span style="color: #339933; font-weight: bold;">_</span> <span style="color: #339933; font-weight: bold;">::</span> <span style="color: #cccc00; font-weight: bold;">Ord</span> t <span style="color: #339933; font-weight: bold;">=&gt;</span> EventG <span style="color: green;">&#40;</span>Improving t<span style="color: green;">&#41;</span> d <span style="color: #339933; font-weight: bold;">-&gt;</span> EventG <span style="color: green;">&#40;</span>Improving t<span style="color: green;">&#41;</span> t</pre></div></div>


<p>Several Synchronous event functions come in pairs like this. The more general version passes along the data of the originating event and the convenient underscore variant doesn&#8217;t. The latter is implemented in terms of the former. With Synchronous, we can implement the more complex version in terms of the simpler version:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">timeE <span style="color: #339933; font-weight: bold;">::</span> Synchronous a TimeT
timeE <span style="color: #339933; font-weight: bold;">=</span> S withTimeE<span style="color: #339933; font-weight: bold;">_</span>
&nbsp;
timeE' <span style="color: #339933; font-weight: bold;">::</span>  Synchronous a <span style="color: green;">&#40;</span>a<span style="color: #339933; font-weight: bold;">,</span> TimeT<span style="color: green;">&#41;</span>
timeE' <span style="color: #339933; font-weight: bold;">=</span> liftA2 <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">,</span><span style="color: green;">&#41;</span> <span style="font-weight: bold;">id</span> timeE
<span style="color: #5d478b; font-style: italic;">-- or, using Beelsebob's Applicative infix library</span>
<span style="color: #5d478b; font-style: italic;">-- timeE' = id &lt;^(,)^&gt; timeE</span>
<span style="color: #5d478b; font-style: italic;">-- or, if we make a default instance (for AFs) for Zip in Conal's TypeCompose</span>
<span style="color: #5d478b; font-style: italic;">-- timeE' = zip id timeE</span></pre></div></div>


<p>Synchronous eliminates the need to have two versions of these functions and saves us the strain of having implement the more complex variants.</p>

<h1>More Synchronous Fun</h1>

<p>Lets pull some more synchronous event transformers into our Synchronous data type:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">prevE<span style="color: #339933; font-weight: bold;">,</span> nextE <span style="color: #339933; font-weight: bold;">::</span> Synchronous a a
prevE <span style="color: #339933; font-weight: bold;">=</span> S withPrevE<span style="color: #339933; font-weight: bold;">_</span>
  <span style="color: #06c; font-weight: bold;">where</span>
    withPrevE<span style="color: #339933; font-weight: bold;">_</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span><span style="font-weight: bold;">fmap</span><span style="color: #339933; font-weight: bold;">.</span><span style="font-weight: bold;">fmap</span><span style="color: green;">&#41;</span> <span style="font-weight: bold;">snd</span> withPrevE
nextE <span style="color: #339933; font-weight: bold;">=</span> S withNextE<span style="color: #339933; font-weight: bold;">_</span>
  <span style="color: #06c; font-weight: bold;">where</span>
    withNextE<span style="color: #339933; font-weight: bold;">_</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span><span style="font-weight: bold;">fmap</span><span style="color: #339933; font-weight: bold;">.</span><span style="font-weight: bold;">fmap</span><span style="color: green;">&#41;</span> <span style="font-weight: bold;">snd</span> withNextE
&nbsp;
mealyE <span style="color: #339933; font-weight: bold;">::</span>  b <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#40;</span>b <span style="color: #339933; font-weight: bold;">-&gt;</span> b<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> Synchronous a b
mealyE a b <span style="color: #339933; font-weight: bold;">=</span> S <span style="color: green;">&#40;</span>mealy<span style="color: #339933; font-weight: bold;">_</span> a b<span style="color: green;">&#41;</span>
&nbsp;
splitE' <span style="color: #339933; font-weight: bold;">::</span>  Event b <span style="color: #339933; font-weight: bold;">-&gt;</span> Synchronous a <span style="color: green;">&#40;</span>Event b<span style="color: green;">&#41;</span>
splitE' <span style="color: #339933; font-weight: bold;">=</span> S <span style="color: #339933; font-weight: bold;">.</span> splitE<span style="color: #339933; font-weight: bold;">_</span>
  <span style="color: #06c; font-weight: bold;">where</span>
    splitE<span style="color: #339933; font-weight: bold;">_</span> <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#40;</span><span style="color: #cccc00; font-weight: bold;">Ord</span> t<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=&gt;</span> EventG t b <span style="color: #339933; font-weight: bold;">-&gt;</span> EventG t a <span style="color: #339933; font-weight: bold;">-&gt;</span> EventG t <span style="color: green;">&#40;</span>EventG t b<span style="color: green;">&#41;</span>
    splitE<span style="color: #339933; font-weight: bold;">_</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span><span style="font-weight: bold;">fmap</span><span style="color: #339933; font-weight: bold;">.</span><span style="font-weight: bold;">fmap</span><span style="color: #339933; font-weight: bold;">.</span><span style="font-weight: bold;">fmap</span><span style="color: green;">&#41;</span> <span style="font-weight: bold;">snd</span> splitE</pre></div></div>


<p>Recall our <code>elapsedFirstTry</code> function from the event tutorial.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">elapsedFirstTry <span style="color: #339933; font-weight: bold;">::</span> Event <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> Event TimeT
elapsedFirstTry e <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">fmap</span> f <span style="color: green;">&#40;</span>withPrevE <span style="color: green;">&#40;</span>withTimeE<span style="color: #339933; font-weight: bold;">_</span> e<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
  <span style="color: #06c; font-weight: bold;">where</span>
    f <span style="color: green;">&#40;</span>tCur<span style="color: #339933; font-weight: bold;">,</span> tPrev<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> tCur <span style="color: #339933; font-weight: bold;">-</span> tPrev</pre></div></div>


<p>Since elapsed is a synchronous event transformer, we no longer need to implement a more complex variant of it. Thinking in terms of synchronous event transformers, we can further simplify the above definition:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">elapsed <span style="color: #339933; font-weight: bold;">::</span>  Synchronous a TimeT
elapsed <span style="color: #339933; font-weight: bold;">=</span> timeE <span style="color: #339933; font-weight: bold;">-</span> <span style="color: green;">&#40;</span>prevE <span style="color: #339933; font-weight: bold;">.</span> timeE<span style="color: green;">&#41;</span></pre></div></div>


<p>This can be read as &#8220;the time minus the previous time&#8221; for each occurrence. Our metronome implementation also sheds some complexity.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #5d478b; font-style: italic;">-- Old definition</span>
metronome <span style="color: #339933; font-weight: bold;">::</span> BellMachine
metronome <span style="color: #339933; font-weight: bold;">=</span> switchE <span style="color: #339933; font-weight: bold;">.</span> <span style="font-weight: bold;">fmap</span> f <span style="color: #339933; font-weight: bold;">.</span> withTimeE <span style="color: #339933; font-weight: bold;">.</span> mealy Idle next <span style="color: #339933; font-weight: bold;">.</span> withElapsed<span style="color: #339933; font-weight: bold;">_</span>
  <span style="color: #06c; font-weight: bold;">where</span>
    f <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>dt<span style="color: #339933; font-weight: bold;">,</span>PlayingCycle<span style="color: green;">&#41;</span><span style="color: #339933; font-weight: bold;">,</span> t<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> period dt t
    f <span style="color: #339933; font-weight: bold;">_</span> <span style="color: #339933; font-weight: bold;">=</span> mempty</pre></div></div>


<p>to</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">metronome <span style="color: #339933; font-weight: bold;">::</span> BellMachine
metronome <span style="color: #339933; font-weight: bold;">=</span> switchE <span style="color: #339933; font-weight: bold;">.</span> toEventT e'
  <span style="color: #06c; font-weight: bold;">where</span>
    e' <span style="color: #339933; font-weight: bold;">=</span> f <span style="color: #339933; font-weight: bold;">&lt;$&gt;</span> mealyE Idle next <span style="color: #339933; font-weight: bold;">&lt;*&gt;</span> timeE <span style="color: #339933; font-weight: bold;">&lt;*&gt;</span> elapsed
      <span style="color: #06c; font-weight: bold;">where</span>
        f PlayingCycle t dt <span style="color: #339933; font-weight: bold;">=</span> period dt t
        f <span style="color: #339933; font-weight: bold;">_</span> <span style="color: #339933; font-weight: bold;">_</span> <span style="color: #339933; font-weight: bold;">_</span> <span style="color: #339933; font-weight: bold;">=</span> mempty</pre></div></div>


<p>Using applicative in this case relieves us from tuple juggling and allows us to express more directly what we&#8217;d like. Note that <code>toEventT</code> was required here because <code>switchE</code> is not a synchronous transformer.</p>

<h1>Arrows</h1>

<p>I&#8217;m not certain it is all that useful, but arrows allow us to use the special <a href="http://www.haskell.org/arrows/syntax.html">arrow syntax</a>. We can rewrite <code>e'</code> this way:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">e' <span style="color: #339933; font-weight: bold;">::</span>  Synchronous a <span style="color: green;">&#40;</span>Event <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
e' <span style="color: #339933; font-weight: bold;">=</span> proc e <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #06c; font-weight: bold;">do</span>
  m <span style="color: #339933; font-weight: bold;">&lt;-</span> mealyE Idle next <span style="color: #339933; font-weight: bold;">-&lt;</span> e
  t <span style="color: #339933; font-weight: bold;">&lt;-</span> timeE <span style="color: #339933; font-weight: bold;">-&lt;</span> e
  dt <span style="color: #339933; font-weight: bold;">&lt;-</span> elapsed <span style="color: #339933; font-weight: bold;">-&lt;</span> e
  returnA <span style="color: #339933; font-weight: bold;">-&lt;</span> <span style="color: #06c; font-weight: bold;">if</span> m <span style="color: #339933; font-weight: bold;">==</span> PlayingCycle <span style="color: #06c; font-weight: bold;">then</span> period t dt
                                  <span style="color: #06c; font-weight: bold;">else</span> mempty</pre></div></div>


<p>&#8211; David Sankel @ <a href="http://anygma.com">Anygma</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://netsuperbrain.com/blog/posts/synchronous-events/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Introducing Reactive: Behaviors</title>
		<link>http://netsuperbrain.com/blog/posts/introducing-reactive-behaviors/</link>
		<comments>http://netsuperbrain.com/blog/posts/introducing-reactive-behaviors/#comments</comments>
		<pubDate>Tue, 02 Dec 2008 16:00:00 +0000</pubDate>
		<dc:creator>David Sankel</dc:creator>
		
		<category><![CDATA[Haskell]]></category>

		<category><![CDATA[Reactive Tutorials]]></category>

		<guid isPermaLink="false">http://netsuperbrain.com/blog/?p=138</guid>
		<description><![CDATA[In the last post, Reactive&#8217;s Events were examined. While Events cover a lot of ground, Reactive&#8217;s Behaviors allow programmers to think beyond sampling when writing games and other interactive programs. This post introduces Behaviors and the functions that make them useful.


Semantically, Behaviors can be thought of as functions of time:



Note that, unlike Events, behaviors do [...]]]></description>
			<content:encoded><![CDATA[<p>In the <a href="http://netsuperbrain.com/blog/posts/introducing-reactive-events">last post</a>, Reactive&#8217;s Events were examined. While Events cover a lot of ground, Reactive&#8217;s Behaviors allow programmers to think beyond sampling when writing games and other interactive programs. This post introduces Behaviors and the functions that make them useful.</p>

<p><span id="more-138"></span>
Semantically, Behaviors can be thought of as functions of time:</p>

<p><center><img src="http://netsuperbrain.com/blog/wp-content/cache/tex_7d7baf1e215c6dfe5172f456d5e58a86.png" align="absmiddle" class="tex" alt="\mbox{\bf type } B_a = T \to a" /></center></p>

<p>Note that, unlike Events, behaviors do not include times at <img src="http://netsuperbrain.com/blog/wp-content/cache/tex_aad18c0a88969b4c1bdc3711475796c2.png" align="absmiddle" class="tex" alt="-\infty" /> and <img src="http://netsuperbrain.com/blog/wp-content/cache/tex_9ab0347369b93587a1fc8dbd6c6a8862.png" align="absmiddle" class="tex" alt="+\infty" />.</p>

<p>Behaviors have a value at all times. The position of a computer mouse is a good example. At any time, there is exactly one position for the mouse. Other behaviors include the data on a hard drive, the color of a pixel, and the sound from speakers.</p>

<p>We&#8217;ll be exploring behaviors through various implementations of a dot machine. This machine consists of a display that has the ability to show any number of dots at arbitrary locations as well as a mouse with one button used for input.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">type</span> Dot <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span><span style="color: #cccc00; font-weight: bold;">Double</span><span style="color: #339933; font-weight: bold;">,</span><span style="color: #cccc00; font-weight: bold;">Double</span><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Input <span style="color: #339933; font-weight: bold;">=</span> I <span style="color: green;">&#123;</span> mouse <span style="color: #339933; font-weight: bold;">::</span> Behavior <span style="color: green;">&#40;</span><span style="color: #cccc00; font-weight: bold;">Double</span><span style="color: #339933; font-weight: bold;">,</span><span style="color: #cccc00; font-weight: bold;">Double</span><span style="color: green;">&#41;</span>
               <span style="color: #339933; font-weight: bold;">,</span> button <span style="color: #339933; font-weight: bold;">::</span> Event <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
               <span style="color: #339933; font-weight: bold;">,</span> integral <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#40;</span>VectorSpace v<span style="color: #339933; font-weight: bold;">,</span> Scalar v <span style="color: #339933; font-weight: bold;">~</span> TimeT<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=&gt;</span> Behavior v <span style="color: #339933; font-weight: bold;">-&gt;</span> Behavior v
               <span style="color: green;">&#125;</span>
<span style="color: #06c; font-weight: bold;">type</span> DotMachine <span style="color: #339933; font-weight: bold;">=</span> Input <span style="color: #339933; font-weight: bold;">-&gt;</span> Behavior <span style="color: green;">&#91;</span>Dot<span style="color: green;">&#93;</span></pre></div></div>


<p>Note that our Input data type also includes an integral function. We&#8217;ll assume that this performs some method of integration over time.</p>

<h2>Simple Examples</h2>

<p>For some basic examples, we&#8217;ll also consider machines that always display one dot.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">type</span> SingleDotMachine <span style="color: #339933; font-weight: bold;">=</span> Input <span style="color: #339933; font-weight: bold;">-&gt;</span> Behavior Dot
toDotMachine <span style="color: #339933; font-weight: bold;">::</span> SingleDotMachine <span style="color: #339933; font-weight: bold;">-&gt;</span> DotMachine
toDotMachine <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span><span style="font-weight: bold;">fmap</span><span style="color: #339933; font-weight: bold;">.</span><span style="font-weight: bold;">fmap</span><span style="color: green;">&#41;</span> pure
<span style="color: #5d478b; font-style: italic;">-- Alt. Def</span>
<span style="color: #5d478b; font-style: italic;">-- toDotMachine s i = fmap (\a -&gt; [a]) (s i)</span></pre></div></div>


<p>Note that <code>fmap</code> applies to behaviors just as it applies to events.</p>

<p>A machine that displays a dot at the mouse location is quite simple:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">atMouse <span style="color: #339933; font-weight: bold;">::</span> SingleDotMachine
atMouse <span style="color: #339933; font-weight: bold;">=</span> mouse</pre></div></div>


<p>Now, consider a machine that displays a dot at the origin of the screen.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">originBA <span style="color: #339933; font-weight: bold;">::</span> SingleDotMachine
originBA <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">const</span> <span style="color: green;">&#40;</span>pure <span style="color: green;">&#40;</span><span style="color: red;">0.0</span><span style="color: #339933; font-weight: bold;">,</span><span style="color: red;">0.0</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
<span style="color: #5d478b; font-style: italic;">-- Alt. Def.</span>
<span style="color: #5d478b; font-style: italic;">-- originBA = (pure.pure) zeroV</span></pre></div></div>


<p><code>pure</code> produces a Behavior that is constant with respect to time. In our case <code>pure (0.0,0.0)</code> creates a Behavior of <code>\t -> (0.0,0.0)</code>.</p>

<p>In the alternate definition, we use <code>zeroV</code> which is a function from the vector-space library and, in our case, is a synonym for <code>(0.0,0.0)</code>.  <code>pure</code>, when applied to functions, is equivalent to <code>const</code>.</p>

<h2>Animation</h2>

<p>One useful built in behavior is one that simply returns the current time as a Double.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">time <span style="color: #339933; font-weight: bold;">::</span> Behavior <span style="color: #cccc00; font-weight: bold;">Double</span></pre></div></div>


<p>time allows us to build simple animations.</p>

<p>Lets implement a machine that orbits the origin.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #5d478b; font-style: italic;">-- Simple Polar to Cartesian conversion</span>
p2c <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#40;</span><span style="color: #cccc00; font-weight: bold;">Floating</span> a<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=&gt;</span> a <span style="color: #339933; font-weight: bold;">-&gt;</span> a <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#40;</span>a<span style="color: #339933; font-weight: bold;">,</span>a<span style="color: green;">&#41;</span>
p2c mag phase <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span>mag<span style="color: #339933; font-weight: bold;">*</span><span style="font-weight: bold;">cos</span> phase<span style="color: #339933; font-weight: bold;">,</span> mag<span style="color: #339933; font-weight: bold;">*</span><span style="font-weight: bold;">sin</span> phase<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- Orbit around the origin with a radius of 10.0</span>
orbit <span style="color: #339933; font-weight: bold;">::</span> Behavior <span style="color: green;">&#40;</span><span style="color: #cccc00; font-weight: bold;">Double</span><span style="color: #339933; font-weight: bold;">,</span><span style="color: #cccc00; font-weight: bold;">Double</span><span style="color: green;">&#41;</span>
orbit <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">fmap</span> <span style="color: green;">&#40;</span>p2c <span style="color: red;">10.0</span><span style="color: green;">&#41;</span> time</pre></div></div>


<p>Behaviors go beyond <code>fmap</code> in that a normal function can be &#8220;lifted&#8221; to apply to behaviors.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">p2cB <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#40;</span><span style="color: #cccc00; font-weight: bold;">Floating</span> a<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=&gt;</span> Behavior a <span style="color: #339933; font-weight: bold;">-&gt;</span> Behavior a <span style="color: #339933; font-weight: bold;">-&gt;</span> Behavior <span style="color: green;">&#40;</span>a<span style="color: #339933; font-weight: bold;">,</span>a<span style="color: green;">&#41;</span>
p2cB <span style="color: #339933; font-weight: bold;">=</span> liftA2 p2c</pre></div></div>


<p>The 2 in <code>liftA2</code> specifies the number of parameters that should be converted to Behaviors. <code>liftA3</code>, and <code>liftA4</code> are also available. These lift functions are defined in terms of a more general <code>&lt;*&gt;</code> operator. To learn more about this mechanism, see <a href="http://en.wikibooks.org/wiki/Haskell/Applicative_Functors">Applicative Functors on Wikibook</a>.</p>

<p>Now we can define a machine with a spiral path:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">spiral <span style="color: #339933; font-weight: bold;">::</span> Behavior <span style="color: green;">&#40;</span><span style="color: #cccc00; font-weight: bold;">Double</span><span style="color: #339933; font-weight: bold;">,</span><span style="color: #cccc00; font-weight: bold;">Double</span><span style="color: green;">&#41;</span>
spiral <span style="color: #339933; font-weight: bold;">=</span> p2cB <span style="color: green;">&#40;</span><span style="font-weight: bold;">fmap</span> <span style="color: green;">&#40;</span>\t <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: red;">10.0</span><span style="color: #339933; font-weight: bold;">*</span><span style="font-weight: bold;">sin</span> t<span style="color: green;">&#41;</span> time<span style="color: green;">&#41;</span> time</pre></div></div>


<h2>Integration</h2>

<p>Reactive&#8217;s integration functions provide us with a straightforward way to incorporate simple physics into our programs. Recall from calculus how to find the position <img src="http://netsuperbrain.com/blog/wp-content/cache/tex_83878c91171338902e0fe0fb97a8c47a.png" align="absmiddle" class="tex" alt="p" /> of an object with an initial position <img src="http://netsuperbrain.com/blog/wp-content/cache/tex_300e8f5ec4863b76b9c7e4e76b349545.png" align="absmiddle" class="tex" alt="p_0" />, an initial velocity <img src="http://netsuperbrain.com/blog/wp-content/cache/tex_8bcda5f030288c05bb245be5d42b3c07.png" align="absmiddle" class="tex" alt="v_0" />, and a constant acceleration of <img src="http://netsuperbrain.com/blog/wp-content/cache/tex_6a9275b7f966e45ffb33492e358c8dff.png" align="absmiddle" class="tex" alt="a_0" />.
<center><img src="http://netsuperbrain.com/blog/wp-content/cache/tex_894a04c1b7c2b6f82bfeb24a4d62498e.png" align="absmiddle" class="tex" alt="a(t) = a_0" /></center>
<center><img src="http://netsuperbrain.com/blog/wp-content/cache/tex_758f9e9c58bf4333a067602bf78c1969.png" align="absmiddle" class="tex" alt="v(t) = v_0 + \int_0^t a" /></center>
<center><img src="http://netsuperbrain.com/blog/wp-content/cache/tex_537f41e0a1eacbda835e8a7a42029792.png" align="absmiddle" class="tex" alt="p(t) = p_0 + \int_0^t v" /></center></p>

<p>In Reactive, this would be implemented as follows:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">a <span style="color: #339933; font-weight: bold;">=</span> pure a0
v <span style="color: #339933; font-weight: bold;">=</span> pure v0 <span style="color: #339933; font-weight: bold;">^+^</span> integral a
p <span style="color: #339933; font-weight: bold;">=</span> pure p0 <span style="color: #339933; font-weight: bold;">^+^</span> integral v</pre></div></div>


<p>There is a trick going on here. Recall that the expression <code>pure v0</code> creates a constant function of time behavior. The plus (<code>^+^</code>) in this case actually adds two behaviors together. The definition of v could also have been written as:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">v <span style="color: #339933; font-weight: bold;">=</span> liftA2 <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">^+^</span><span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>pure v0<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>integral a<span style="color: green;">&#41;</span>
<span style="color: #5d478b; font-style: italic;">-- or even simpler</span>
v <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">fmap</span> <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">^+^</span> v0<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>integral a<span style="color: green;">&#41;</span></pre></div></div>


<p>Reactive provides a vector space instance for behaviors of vectors space instances. Instances are also supplied for the various <code>Num</code> classes so you can feel free to use the normal <code>+</code> operator on two behaviors of Doubles, for example.</p>

<p>Consider a dot machine where the dot starts at the origin and is attracted towards the mouse. The further away the dot is, the faster it moves towards the mouse position.</p>

<p>First, we&#8217;ll use a general attractor function:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">attract <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#40;</span>Behavior Dot<span style="color: #339933; font-weight: bold;">-&gt;</span>Behavior Dot<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #5d478b; font-style: italic;">-- The integral function</span>
           Dot <span style="color: #339933; font-weight: bold;">-&gt;</span>                          <span style="color: #5d478b; font-style: italic;">-- The initial position</span>
           Behavior Dot <span style="color: #339933; font-weight: bold;">-&gt;</span>                 <span style="color: #5d478b; font-style: italic;">-- The behavior to attract towards</span>
           Behavior Dot
attract int pos0 attractor <span style="color: #339933; font-weight: bold;">=</span> pos
  <span style="color: #06c; font-weight: bold;">where</span>
    pos <span style="color: #339933; font-weight: bold;">::</span> Behavior Dot
    pos <span style="color: #339933; font-weight: bold;">=</span> pure pos0 <span style="color: #339933; font-weight: bold;">^+^</span> int vel
    vel <span style="color: #339933; font-weight: bold;">::</span> Behavior Dot
    vel <span style="color: #339933; font-weight: bold;">=</span> pos <span style="color: #339933; font-weight: bold;">^-^</span> attractor</pre></div></div>


<p>Now the dot machine implementation is quite simple.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">followMouse <span style="color: #339933; font-weight: bold;">::</span> SingleDotMachine
followMouse i <span style="color: #339933; font-weight: bold;">=</span> attract <span style="color: green;">&#40;</span>integral i<span style="color: green;">&#41;</span> zeroV <span style="color: green;">&#40;</span>mouse i<span style="color: green;">&#41;</span></pre></div></div>


<h2>Behaviors with Events</h2>

<p>Reactive includes several functions involving both <code>Behaviors</code> and <code>Events</code>, the most primitive being <code>stepper</code> and <code>snapshot</code>.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #5d478b; font-style: italic;">-- | Discretely changing behavior, based on an initial value and a</span>
<span style="color: #5d478b; font-style: italic;">-- new-value event.</span>
stepper <span style="color: #339933; font-weight: bold;">::</span>  a <span style="color: #339933; font-weight: bold;">-&gt;</span> Event a <span style="color: #339933; font-weight: bold;">-&gt;</span> Behavior a
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- Snapshot a behavior whenever an event occurs.</span>
snapshot <span style="color: #339933; font-weight: bold;">::</span> Behavior b <span style="color: #339933; font-weight: bold;">-&gt;</span> Event a <span style="color: #339933; font-weight: bold;">-&gt;</span> Event <span style="color: green;">&#40;</span>a<span style="color: #339933; font-weight: bold;">,</span> b<span style="color: green;">&#41;</span>
snapshot<span style="color: #339933; font-weight: bold;">_</span> <span style="color: #339933; font-weight: bold;">::</span> Behavior b <span style="color: #339933; font-weight: bold;">-&gt;</span> Event a <span style="color: #339933; font-weight: bold;">-&gt;</span> Event b</pre></div></div>


<p>Using the above functions, we can make a machine that shows a dot at the origin until the button is pressed, in which case it will appear at the mouse position.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">mouseAtPress <span style="color: #339933; font-weight: bold;">::</span> Input <span style="color: #339933; font-weight: bold;">-&gt;</span> Event Dot
mouseAtPress i <span style="color: #339933; font-weight: bold;">=</span> snapshot<span style="color: #339933; font-weight: bold;">_</span> <span style="color: green;">&#40;</span>mouse i<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>button i<span style="color: green;">&#41;</span>
<span style="color: #5d478b; font-style: italic;">-- Alt. Def.</span>
<span style="color: #5d478b; font-style: italic;">-- mouseAtPress = liftA2 snapshot_ mouse button</span>
&nbsp;
wherePressed <span style="color: #339933; font-weight: bold;">::</span> SingleDotMachine
wherePressed <span style="color: #339933; font-weight: bold;">=</span> stepper zeroV <span style="color: #339933; font-weight: bold;">.</span> mouseAtPress</pre></div></div>


<p>If we instead want a dot to continue being displayed, we&#8217;ll collect the events,</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">collectE <span style="color: #339933; font-weight: bold;">::</span> Event a <span style="color: #339933; font-weight: bold;">-&gt;</span> Event <span style="color: green;">&#91;</span>a<span style="color: green;">&#93;</span>
collectE <span style="color: #339933; font-weight: bold;">=</span> monoidE <span style="color: #339933; font-weight: bold;">.</span> <span style="font-weight: bold;">fmap</span> pure
<span style="color: #5d478b; font-style: italic;">-- Alt def.</span>
<span style="color: #5d478b; font-style: italic;">-- collectE = scanlE (++) [] . fmap (\a -&gt; [a])</span></pre></div></div>


<p>, make them into a behavior,</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">collectEB <span style="color: #339933; font-weight: bold;">::</span> Event a <span style="color: #339933; font-weight: bold;">-&gt;</span> Behavior <span style="color: green;">&#91;</span>a<span style="color: green;">&#93;</span>
collectEB <span style="color: #339933; font-weight: bold;">=</span> stepper mempty <span style="color: #339933; font-weight: bold;">.</span> collectE
<span style="color: #5d478b; font-style: italic;">-- Alt def.</span>
<span style="color: #5d478b; font-style: italic;">-- collectEB = stepper [] . collectE</span></pre></div></div>


<p>, and put it together:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">atCursor <span style="color: #339933; font-weight: bold;">::</span> DotMachine
atCursor <span style="color: #339933; font-weight: bold;">=</span> collectEB <span style="color: #339933; font-weight: bold;">.</span> mouseAtPress</pre></div></div>


<h2>Dynamic Collections</h2>

<p>The <code>atCursor</code> example included a dynamically changing collection, a list of dots. What if instead we wanted a list of interactive behaviors instead? It turns out that this is difficult to implement in reactive as it is now. At the time of this writing reactive is being revamped for this purpose.</p>

<h2>What&#8217;s Next</h2>

<p>In the next article, I&#8217;ll conclude this series by taking a look at legacy adapters which enable our reactive programs to connect with the IO monad.</p>

<h2>Acknowledgments</h2>

<p>This tutorial was created by David Sankel with help from Thomas Davie and was sponsored by <a href="http://www.anygma.com">Anygma</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://netsuperbrain.com/blog/posts/introducing-reactive-behaviors/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Why is the Reactive Behavior tutorial taking so long? splitB</title>
		<link>http://netsuperbrain.com/blog/posts/why-is-the-reactive-behavior-tutorial-taking-so-long-splitb/</link>
		<comments>http://netsuperbrain.com/blog/posts/why-is-the-reactive-behavior-tutorial-taking-so-long-splitb/#comments</comments>
		<pubDate>Mon, 24 Nov 2008 20:58:41 +0000</pubDate>
		<dc:creator>David Sankel</dc:creator>
		
		<category><![CDATA[Haskell]]></category>

		<category><![CDATA[frp]]></category>

		<category><![CDATA[reactive]]></category>

		<guid isPermaLink="false">http://netsuperbrain.com/blog/?p=189</guid>
		<description><![CDATA[Writing the event tutorial brought out the need for several basic functions in Reactive, especially switchE. The behavior tutorial is also bringing with it a slew of necessary functions. The most surprisingly difficult to implement has been splitB.


-- &#124;At every event occurrence, produce a behavior that is a combination of the
-- first and second where [...]]]></description>
			<content:encoded><![CDATA[<p>Writing the event tutorial brought out the need for several basic functions in Reactive, especially switchE. The behavior tutorial is also bringing with it a slew of necessary functions. The most surprisingly difficult to implement has been splitB.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #5d478b; font-style: italic;">-- |At every event occurrence, produce a behavior that is a combination of the</span>
<span style="color: #5d478b; font-style: italic;">-- first and second where it acts like the first up to the event occurrence</span>
<span style="color: #5d478b; font-style: italic;">-- and then acts like the second.</span>
splitB <span style="color: #339933; font-weight: bold;">::</span> Behavior a <span style="color: #339933; font-weight: bold;">-&gt;</span>
          Behavior a <span style="color: #339933; font-weight: bold;">-&gt;</span>
          Event b    <span style="color: #339933; font-weight: bold;">-&gt;</span> 
          Event <span style="color: green;">&#40;</span>b<span style="color: #339933; font-weight: bold;">,</span>Behavior a<span style="color: green;">&#41;</span></pre></div></div>


<p>This post describes how this function was implemented. In doing so, we&#8217;ll explore internals of the Reactive library and come into contact with the tricky laziness issues that often come up when working with Reactive.
<span id="more-189"></span></p>

<p>Some of this code will be using (fmap.fmap) style. If that&#8217;s unfamiliar, see Peter Verswyvelen&#8217;s great <a href="http://www.haskell.org/pipermail/reactive/2008-November/000054.html">mini tutorial</a> on it.</p>

<h1>Motivation</h1>

<p>The following graph shows a mouse&#8217;s x axis position information over a period of time with time 0 representing when the program starts. The y axis represents the x position and the x axis represents time. If you look close, you&#8217;ll notice that the graph consists of dots representing samples of the mouse position. The position of the mouse between these samples is unknown by the computer.</p>

<p><a href="http://netsuperbrain.com/blog/wp-content/uploads/2008/11/step-0.png"><img src="http://netsuperbrain.com/blog/wp-content/uploads/2008/11/step-0-300x224.png" alt="" title="splitB step-0" width="300" height="224" class="alignnone size-medium wp-image-196" /></a></p>

<p>In Reactive, we like to think of such things as continuous. In reactive-glut, for example, the mouse&#8217;s x position is represented as a continuous line, as in the following graph. At times before the program begins, all the way to <img src="http://netsuperbrain.com/blog/wp-content/cache/tex_aad18c0a88969b4c1bdc3711475796c2.png" align="absmiddle" class="tex" alt="-\infty" />, the position is <img src="http://netsuperbrain.com/blog/wp-content/cache/tex_7814a0e7fffecda9cebb60d2bc160257.png" align="absmiddle" class="tex" alt="\bot" />.</p>

<p><a href="http://netsuperbrain.com/blog/wp-content/uploads/2008/11/step-1.png"><img src="http://netsuperbrain.com/blog/wp-content/uploads/2008/11/step-1-300x224.png" alt="" title="splitB step-1" width="300" height="224" class="alignnone size-medium wp-image-198" /></a></p>

<p>Several useful reactive programs involve dynamic collections where a responsive entity comes to life at a certain time. In this case, we would like the entity&#8217;s knowledge of the universe to begin only after it&#8217;s creation. Aside from modeling the domain well, it sidesteps the possibility of a memory leak.</p>

<p>In the following graph we show what an entity might see of the x mouse position after its creation at time t.</p>

<p><a href="http://netsuperbrain.com/blog/wp-content/uploads/2008/11/step-2.png"><img src="http://netsuperbrain.com/blog/wp-content/uploads/2008/11/step-2-300x202.png" alt="" title="splitB step-2" width="300" height="202" class="alignnone size-medium wp-image-207" /></a></p>

<h1>splitB</h1>

<p>Our solution to the above issues is a general function called splitB:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #5d478b; font-style: italic;">-- |At every event occurrence, produce a behavior that is a combination of the</span>
<span style="color: #5d478b; font-style: italic;">-- first and second where it acts like the first up to the event occurrence</span>
<span style="color: #5d478b; font-style: italic;">-- and then acts like the second.</span>
splitB <span style="color: #339933; font-weight: bold;">::</span> Behavior a <span style="color: #339933; font-weight: bold;">-&gt;</span>
          Behavior a <span style="color: #339933; font-weight: bold;">-&gt;</span>
          Event b    <span style="color: #339933; font-weight: bold;">-&gt;</span> 
          Event <span style="color: green;">&#40;</span>b<span style="color: #339933; font-weight: bold;">,</span>Behavior a<span style="color: green;">&#41;</span></pre></div></div>


<p>To do the splitting as mentioned in the mouse example, we can specialize <code>splitB</code> to:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">splitBBot <span style="color: #339933; font-weight: bold;">::</span> Behavior a <span style="color: #339933; font-weight: bold;">-&gt;</span> Event b <span style="color: #339933; font-weight: bold;">-&gt;</span> Event <span style="color: green;">&#40;</span>b<span style="color: #339933; font-weight: bold;">,</span> Behavior a<span style="color: green;">&#41;</span>
splitBBot <span style="color: #339933; font-weight: bold;">=</span> splitB <span style="color: green;">&#40;</span>pure <span style="color: green;">&#40;</span><span style="font-weight: bold;">error</span> <span style="background-color: #3cb371;">&quot;splitBBot: no data&quot;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre></div></div>


<h1>A naive implementation</h1>

<p>Lets start with a naive implementation:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">splitB <span style="color: #339933; font-weight: bold;">::</span> Behavior a <span style="color: #339933; font-weight: bold;">-&gt;</span> Behavior a <span style="color: #339933; font-weight: bold;">-&gt;</span> Event b <span style="color: #339933; font-weight: bold;">-&gt;</span> Event <span style="color: green;">&#40;</span>b<span style="color: #339933; font-weight: bold;">,</span> Behavior a<span style="color: green;">&#41;</span>
splitB bLeft bRight e <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">fmap</span> f <span style="color: green;">&#40;</span>withTimeE e<span style="color: green;">&#41;</span>
  <span style="color: #06c; font-weight: bold;">where</span>
    f <span style="color: green;">&#40;</span>b<span style="color: #339933; font-weight: bold;">,</span>ot<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span>b<span style="color: #339933; font-weight: bold;">,</span> iffB <span style="color: green;">&#40;</span><span style="font-weight: bold;">fmap</span> <span style="color: green;">&#40;</span>ot <span style="color: #339933; font-weight: bold;">&gt;=</span><span style="color: green;">&#41;</span> time<span style="color: green;">&#41;</span> bLeft bRight<span style="color: green;">&#41;</span>
&nbsp;
iffB <span style="color: #339933; font-weight: bold;">::</span> Behavior <span style="color: #cccc00; font-weight: bold;">Bool</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> Behavior a <span style="color: #339933; font-weight: bold;">-&gt;</span> Behavior a <span style="color: #339933; font-weight: bold;">-&gt;</span> Behavior a
iffB <span style="color: #339933; font-weight: bold;">=</span> liftA3 iff
&nbsp;
iff a b c <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #06c; font-weight: bold;">if</span> a <span style="color: #06c; font-weight: bold;">then</span> b <span style="color: #06c; font-weight: bold;">else</span> c</pre></div></div>


<p>Semantically, the above splitB implementation is correct. Unfortunately, there is a rather large operational issue: whenever the resultant events are evaluated, a traversal of the entire <code>bRight</code> behavior occurs. This CPU and memory leak amounts to a reactive head explosion.</p>

<h1>Something Better</h1>

<p>What we need is a decent forgetter mechanism. For our first try we&#8217;ll reduce the behavior problem into a reactive problem.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">unb <span style="color: #339933; font-weight: bold;">::</span> BehaviorG tr tf a <span style="color: #339933; font-weight: bold;">-&gt;</span> ReactiveG tr <span style="color: green;">&#40;</span>Fun tf a<span style="color: green;">&#41;</span>
beh <span style="color: #339933; font-weight: bold;">::</span> ReactiveG tr <span style="color: green;">&#40;</span>Fun tf a<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> BehaviorG tr tf a</pre></div></div>


<p>The above functions convert a behavior into a reactive of time functions and vice-versa. It&#8217;s important to note that unb doesn&#8217;t have a semantic meaning and wouldn&#8217;t be used in normal code. The G&#8217;s in these signatures represent &#8220;General&#8221; in the aspect that the time types (tr and tf) are not fixed to any specific data type. The typical Event and Behavior types have tr and tf set to Double.</p>

<p>Now we can reduce our <code>splitB</code> implementation into an equivalent <code>splitR</code> implementation.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">splitB l r e <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">fmap</span> <span style="color: green;">&#40;</span>second beh<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>splitR <span style="color: green;">&#40;</span>unb l<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>unb r<span style="color: green;">&#41;</span> e<span style="color: green;">&#41;</span>
&nbsp;
splitR <span style="color: #339933; font-weight: bold;">::</span> <span style="color: #cccc00; font-weight: bold;">Ord</span> t <span style="color: #339933; font-weight: bold;">=&gt;</span> ReactiveG t a <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #5d478b; font-style: italic;">-- left</span>
                   ReactiveG t a <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #5d478b; font-style: italic;">-- right</span>
                   EventG t b <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #5d478b; font-style: italic;">-- Split locations</span>
                   EventG t <span style="color: green;">&#40;</span>b<span style="color: #339933; font-weight: bold;">,</span> ReactiveG t a<span style="color: green;">&#41;</span> <span style="color: #5d478b; font-style: italic;">-- results</span></pre></div></div>


<p>Lets assume we have a <code>glueR</code> for reactive that chops the right side of its first argument at time t, chops the left side of its second argument at time t, and glues the two pieces together:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">glueR <span style="color: #339933; font-weight: bold;">::</span> <span style="color: #cccc00; font-weight: bold;">Ord</span> t <span style="color: #339933; font-weight: bold;">=&gt;</span> ReactiveG t a <span style="color: #339933; font-weight: bold;">-&gt;</span>  <span style="color: #5d478b; font-style: italic;">-- left</span>
                  ReactiveG t a <span style="color: #339933; font-weight: bold;">-&gt;</span>  <span style="color: #5d478b; font-style: italic;">-- right</span>
                  Time t <span style="color: #339933; font-weight: bold;">-&gt;</span>
                  ReactiveG t a <span style="color: #5d478b; font-style: italic;">-- combination of left and right with time t in the middle</span></pre></div></div>


<p>We may now implement <code>splitR</code>:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">splitR <span style="color: #339933; font-weight: bold;">::</span> <span style="color: #cccc00; font-weight: bold;">Ord</span> t <span style="color: #339933; font-weight: bold;">=&gt;</span> ReactiveG t a <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #5d478b; font-style: italic;">-- left</span>
                   ReactiveG t a <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #5d478b; font-style: italic;">-- right</span>
                   EventG t b <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #5d478b; font-style: italic;">-- Split locations</span>
                   EventG t <span style="color: green;">&#40;</span>b<span style="color: #339933; font-weight: bold;">,</span> ReactiveG t a<span style="color: green;">&#41;</span> <span style="color: #5d478b; font-style: italic;">-- results</span>
splitR l r s <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">fmap</span> <span style="font-weight: bold;">snd</span> <span style="color: green;">&#40;</span>scanlE f <span style="color: green;">&#40;</span>r<span style="color: #339933; font-weight: bold;">,</span><span style="font-weight: bold;">error</span> <span style="background-color: #3cb371;">&quot;splitR, shouldn't see it&quot;</span><span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>withTimeGE s<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
  <span style="color: #06c; font-weight: bold;">where</span>
    f <span style="color: green;">&#40;</span>r<span style="color: #339933; font-weight: bold;">,_</span><span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>b<span style="color: #339933; font-weight: bold;">,</span>t<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span>c<span style="color: #339933; font-weight: bold;">,</span> <span style="color: green;">&#40;</span>b<span style="color: #339933; font-weight: bold;">,</span>c<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
      <span style="color: #06c; font-weight: bold;">where</span>
        c <span style="color: #339933; font-weight: bold;">=</span> glueR l r t</pre></div></div>


<p>The above implementation uses scanlE to pass along the previous occurrence&#8217;s result to serve as a condensed version of the &#8220;right&#8221; reactive. We&#8217;ll deconstruct the <code>Reactive</code> data type to implement <code>glueR</code> in terms of <code>glueE</code>:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">glueR <span style="color: #339933; font-weight: bold;">::</span> <span style="color: #cccc00; font-weight: bold;">Ord</span> t <span style="color: #339933; font-weight: bold;">=&gt;</span> ReactiveG t a <span style="color: #339933; font-weight: bold;">-&gt;</span>  ReactiveG t a <span style="color: #339933; font-weight: bold;">-&gt;</span> Time t <span style="color: #339933; font-weight: bold;">-&gt;</span> ReactiveG t a
glueR <span style="color: #339933; font-weight: bold;">_</span> r <span style="color: green;">&#40;</span>Max MinBound<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> r
glueR l r <span style="color: green;">&#40;</span>Max MaxBound<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> l
glueR <span style="color: green;">&#40;</span>Stepper al el<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>Stepper ar er<span style="color: green;">&#41;</span> t <span style="color: #339933; font-weight: bold;">=</span> Stepper al <span style="color: green;">&#40;</span>glueE t el er<span style="color: green;">&#41;</span></pre></div></div>


<p>In the above function, we see that a Reactive internally consists of an initial value and an event who&#8217;s occurrences represent possible changes.</p>

<p>Implementation of <code>glueE</code> is straightforward:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">glueE <span style="color: #339933; font-weight: bold;">::</span> <span style="color: #cccc00; font-weight: bold;">Ord</span> t <span style="color: #339933; font-weight: bold;">=&gt;</span> Time t <span style="color: #339933; font-weight: bold;">-&gt;</span> EventG t a <span style="color: #339933; font-weight: bold;">-&gt;</span> EventG t a <span style="color: #339933; font-weight: bold;">-&gt;</span> EventG t a
glueE k <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span><span style="font-weight: bold;">fmap</span><span style="color: #339933; font-weight: bold;">.</span><span style="font-weight: bold;">fmap</span><span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>join <span style="color: #339933; font-weight: bold;">.</span> <span style="font-weight: bold;">fmap</span> <span style="color: green;">&#40;</span>f k<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">.</span> withTimeGE<span style="color: green;">&#41;</span> eitherE
  <span style="color: #06c; font-weight: bold;">where</span>
    f k <span style="color: green;">&#40;</span>e<span style="color: #339933; font-weight: bold;">,</span>t<span style="color: green;">&#41;</span> | t <span style="color: #339933; font-weight: bold;">&lt;</span> k     <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">either</span> pure <span style="color: green;">&#40;</span>pure mempty<span style="color: green;">&#41;</span> e
              | <span style="font-weight: bold;">otherwise</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">either</span> <span style="color: green;">&#40;</span>pure mempty<span style="color: green;">&#41;</span> pure e</pre></div></div>


<h2>Thoughts</h2>

<p>Our implementation of splitB certainly helps with our naive implementation&#8217;s memory and CPU leak. Unfortunately, when an occurrence is evaluated, all the behavior&#8217;s steps since the previous occurrence must still be traversed.</p>

<h1>Much Better, but Very Tricky</h1>

<p>Ideally, we would like each our occurrences to do no traversal when evaluated. If the prior event&#8217;s evaluation of the behavior caused concurrent evaluation of the current behavior, before it occurred, we can get this.</p>

<p>Lets look at a different implementation (note the different type signature) of glueE</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">glueE <span style="color: #339933; font-weight: bold;">::</span> <span style="color: #cccc00; font-weight: bold;">Ord</span> t <span style="color: #339933; font-weight: bold;">=&gt;</span>   Time t  <span style="color: #339933; font-weight: bold;">-&gt;</span>
                 EventG t a <span style="color: #339933; font-weight: bold;">-&gt;</span>  <span style="color: #5d478b; font-style: italic;">-- left</span>
                 EventG t a <span style="color: #339933; font-weight: bold;">-&gt;</span>  <span style="color: #5d478b; font-style: italic;">-- right</span>
                 <span style="color: green;">&#40;</span>EventG t a<span style="color: #339933; font-weight: bold;">,</span>   <span style="color: #5d478b; font-style: italic;">-- right event</span>
                  EventG t a<span style="color: green;">&#41;</span>   <span style="color: #5d478b; font-style: italic;">-- combination of left and right</span>
glueE k l r <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #06c; font-weight: bold;">if</span> k <span style="color: #339933; font-weight: bold;">&lt;</span> <span style="font-weight: bold;">min</span> lt rt
               <span style="color: #06c; font-weight: bold;">then</span> <span style="color: green;">&#40;</span>r<span style="color: #339933; font-weight: bold;">,</span>r<span style="color: green;">&#41;</span>
               <span style="color: #06c; font-weight: bold;">else</span> <span style="color: #06c; font-weight: bold;">if</span> lt <span style="color: #339933; font-weight: bold;">&lt;</span> rt
                      <span style="color: #06c; font-weight: bold;">then</span> second <span style="color: green;">&#40;</span>mappend <span style="color: green;">&#40;</span>once l<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>glueE k <span style="color: green;">&#40;</span>restE l<span style="color: green;">&#41;</span> r<span style="color: green;">&#41;</span>
                      <span style="color: #06c; font-weight: bold;">else</span> first  <span style="color: green;">&#40;</span>mappend <span style="color: green;">&#40;</span>once r<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>glueE k l <span style="color: green;">&#40;</span>restE r<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
  <span style="color: #06c; font-weight: bold;">where</span>
    lt <span style="color: #339933; font-weight: bold;">=</span> firstETime l
    rt <span style="color: #339933; font-weight: bold;">=</span> firstETime r
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- If there is an occurrence, return the time of the first occurrence,</span>
<span style="color: #5d478b; font-style: italic;">-- otherwise return +infty</span>
firstETime <span style="color: #339933; font-weight: bold;">::</span> <span style="color: #cccc00; font-weight: bold;">Ord</span> t <span style="color: #339933; font-weight: bold;">=&gt;</span> EventG t a <span style="color: #339933; font-weight: bold;">-&gt;</span> Time t
firstETime <span style="color: #339933; font-weight: bold;">=</span> futTime <span style="color: #339933; font-weight: bold;">.</span> eFuture</pre></div></div>


<p><code>glueE</code> returns a copy of its right event and is completely identical semantically. However, the right event that is returned is now is written in <em>terms</em> of the combination. If one incrementally starts evaluating the returned right event, they are also evaluating the combination event at the same time. Think about it.</p>

<p>We can expand this to our glueR implementation:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">glueR <span style="color: #339933; font-weight: bold;">::</span> <span style="color: #cccc00; font-weight: bold;">Ord</span> t <span style="color: #339933; font-weight: bold;">=&gt;</span> ReactiveG t a <span style="color: #339933; font-weight: bold;">-&gt;</span>  <span style="color: #5d478b; font-style: italic;">-- left</span>
                  ReactiveG t a <span style="color: #339933; font-weight: bold;">-&gt;</span>  <span style="color: #5d478b; font-style: italic;">-- right</span>
                  Time t <span style="color: #339933; font-weight: bold;">-&gt;</span>
                  <span style="color: green;">&#40;</span> ReactiveG t a   <span style="color: #5d478b; font-style: italic;">-- right</span>
                  <span style="color: #339933; font-weight: bold;">,</span> ReactiveG t a <span style="color: green;">&#41;</span> <span style="color: #5d478b; font-style: italic;">-- combination of left and right</span>
glueR <span style="color: #339933; font-weight: bold;">_</span> r <span style="color: green;">&#40;</span>Max MinBound<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span>r<span style="color: #339933; font-weight: bold;">,</span> r<span style="color: green;">&#41;</span>
glueR l r <span style="color: green;">&#40;</span>Max MaxBound<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span>r<span style="color: #339933; font-weight: bold;">,</span> l<span style="color: green;">&#41;</span>
glueR <span style="color: green;">&#40;</span>Stepper al el<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>Stepper ar er<span style="color: green;">&#41;</span> t <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span>Stepper ar <span style="color: #339933; font-weight: bold;">***</span> Stepper al<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>glueE t el er<span style="color: green;">&#41;</span></pre></div></div>


<p>Finally, we put this together for our fully optimized splitR</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">splitR <span style="color: #339933; font-weight: bold;">::</span> <span style="color: #cccc00; font-weight: bold;">Ord</span> t <span style="color: #339933; font-weight: bold;">=&gt;</span> ReactiveG t a <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #5d478b; font-style: italic;">-- left</span>
                   ReactiveG t a <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #5d478b; font-style: italic;">-- right</span>
                   EventG t b <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #5d478b; font-style: italic;">-- Split locations</span>
                   EventG t <span style="color: green;">&#40;</span>b<span style="color: #339933; font-weight: bold;">,</span> ReactiveG t a<span style="color: green;">&#41;</span> <span style="color: #5d478b; font-style: italic;">-- results</span>
splitR l r s <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">fmap</span> g <span style="color: green;">&#40;</span>withNextE <span style="color: green;">&#40;</span><span style="font-weight: bold;">fmap</span> <span style="font-weight: bold;">snd</span> <span style="color: green;">&#40;</span>scanlE f <span style="color: green;">&#40;</span>l<span style="color: #339933; font-weight: bold;">,</span><span style="font-weight: bold;">error</span> <span style="background-color: #3cb371;">&quot;splitR, shouldn't see it&quot;</span><span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>withTimeGE s<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
  <span style="color: #06c; font-weight: bold;">where</span>
    f <span style="color: green;">&#40;</span>cPrev<span style="color: #339933; font-weight: bold;">,_</span><span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>b<span style="color: #339933; font-weight: bold;">,</span>t<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span>c<span style="color: #339933; font-weight: bold;">,</span> <span style="color: green;">&#40;</span>b<span style="color: #339933; font-weight: bold;">,</span>c<span style="color: #339933; font-weight: bold;">,</span>cPrev'<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
      <span style="color: #06c; font-weight: bold;">where</span>
        <span style="color: green;">&#40;</span>cPrev'<span style="color: #339933; font-weight: bold;">,</span>c<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> glueR l cPrev t
    g <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>b<span style="color: #339933; font-weight: bold;">,</span>c<span style="color: #339933; font-weight: bold;">,_</span><span style="color: green;">&#41;</span><span style="color: #339933; font-weight: bold;">,</span> <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">_,_,</span>c'<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span>b<span style="color: #339933; font-weight: bold;">,</span>c'<span style="color: green;">&#41;</span></pre></div></div>


<p>The <code>(fmap snd (scanlE f...</code> part returns a triple (b,c,cPrev) where b is the value at the event splitter, c is the combination of the reactives at that event, and cPrev is the combination of the reactives at the previous event. cPrev is identical to c in the prior occurrence, however it has gone through that special transformation in glueR.</p>

<p><code>fmap g (withNextE...</code> replaces the c in the triples with the cPrev in the subsequent event. The resulting 2-tuple is the answer.</p>

<h1>Conclusion</h1>

<p>If one has a widget of type <code>UI -> Geometry3</code> we can now take a simple UI type:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">data</span> UI <span style="color: #339933; font-weight: bold;">=</span> UI <span style="color: green;">&#123;</span>
  mousePosition      <span style="color: #339933; font-weight: bold;">::</span> Behavior <span style="color: green;">&#40;</span><span style="color: #cccc00; font-weight: bold;">Double</span><span style="color: #339933; font-weight: bold;">,</span><span style="color: #cccc00; font-weight: bold;">Double</span><span style="color: green;">&#41;</span><span style="color: #339933; font-weight: bold;">,</span>
  leftButtonPressed  <span style="color: #339933; font-weight: bold;">::</span> Event <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span><span style="color: #339933; font-weight: bold;">,</span>
  rightButtonPressed <span style="color: #339933; font-weight: bold;">::</span> Event <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span><span style="color: #339933; font-weight: bold;">,</span>
  keyPressed         <span style="color: #339933; font-weight: bold;">::</span> Event Key<span style="color: #339933; font-weight: bold;">,</span>
  framePass          <span style="color: #339933; font-weight: bold;">::</span> Event <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
<span style="color: green;">&#125;</span></pre></div></div>


<p>And define a function that will allow for new widgets to be created on command without worry of memory leak.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">splitUiBot <span style="color: #339933; font-weight: bold;">::</span> Ui <span style="color: #339933; font-weight: bold;">-&gt;</span> Event b <span style="color: #339933; font-weight: bold;">-&gt;</span> Event <span style="color: green;">&#40;</span>b<span style="color: #339933; font-weight: bold;">,</span>Ui<span style="color: green;">&#41;</span></pre></div></div>


<p>Hint: We&#8217;ll also need the use of a more general version of splitE.</p>

<p>Alright, now I can get back to writing that Behavior tutorial!</p>
]]></content:encoded>
			<wfw:commentRss>http://netsuperbrain.com/blog/posts/why-is-the-reactive-behavior-tutorial-taking-so-long-splitb/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Introducing Reactive: Events</title>
		<link>http://netsuperbrain.com/blog/posts/introducing-reactive-events/</link>
		<comments>http://netsuperbrain.com/blog/posts/introducing-reactive-events/#comments</comments>
		<pubDate>Fri, 07 Nov 2008 15:16:27 +0000</pubDate>
		<dc:creator>David Sankel</dc:creator>
		
		<category><![CDATA[Haskell]]></category>

		<category><![CDATA[Reactive Tutorials]]></category>

		<guid isPermaLink="false">http://netsuperbrain.com/blog/?p=10</guid>
		<description><![CDATA[Reactive is Conal Elliott&#8217;s newest FRP (functional reactive programming) framework. In this series of blog posts, I&#8217;m going to introduce a set of examples by concept. These articles are intended to serve as tutorials and motivation for writing interactive programs using Reactive instead of the IO monad.

A basic knowledge of Haskell and the prelude functions, [...]]]></description>
			<content:encoded><![CDATA[<p>Reactive is Conal Elliott&#8217;s newest FRP (functional reactive programming) framework. In this series of blog posts, I&#8217;m going to introduce a set of examples by concept. These articles are intended to serve as tutorials and motivation for writing interactive programs using Reactive instead of the IO monad.</p>

<p>A basic knowledge of Haskell and the prelude functions, especially higher order functions like <code>id</code> and <code>const</code>, is all that is required.</p>

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

<p>We&#8217;ll start our journey by taking a look at events. Semantically, Events can be <em>thought of</em> as lists of time/value pairs where the times are non-decreasing:</p>

<p><center><img src="http://netsuperbrain.com/blog/wp-content/cache/tex_6c729d205cef70a91463185979bff72e.png" align="absmiddle" class="tex" alt="\mbox{\bf type } E_a = [(\hat{T},a)]" /></center></p>

<p>Some varied examples:</p>

<ul>
<li>
<ul>
<li><code>[(1.0, 'h'), (2.0, 'e'), (3.0, 'l'), (3.1,'l'), (4.0,'o')]</code> could be a keyboard event (<code>Event Char</code>) where the user typed &#8220;hello&#8221; pressing the keys at those times.</li>
</ul></li>
<li>
<ul>
<li><code>[(50.0,FSharp), (50.0,ASharp), (50.0,CSharp)]</code> could refer to three notes being plucked on a guitar at time 50.</li>
</ul></li>
<li>
<ul>
<li>[(<img src="http://netsuperbrain.com/blog/wp-content/cache/tex_aad18c0a88969b4c1bdc3711475796c2.png" align="absmiddle" class="tex" alt="-\infty" />, ()), (0, ()), (5, ())] is an event that has an occurrence that happens before time. Note that events stretch time to include values at <img src="http://netsuperbrain.com/blog/wp-content/cache/tex_aad18c0a88969b4c1bdc3711475796c2.png" align="absmiddle" class="tex" alt="-\infty" /> and <img src="http://netsuperbrain.com/blog/wp-content/cache/tex_9ab0347369b93587a1fc8dbd6c6a8862.png" align="absmiddle" class="tex" alt="+\infty" />. This is what the carot (^) signifies in the definition of <img src="http://netsuperbrain.com/blog/wp-content/cache/tex_08f4ad80a2083e76ed11bdbd090de249.png" align="absmiddle" class="tex" alt="E_a" /> above.</li>
</ul></li>
<li>
<ul>
<li><code>[ (1,()), (0,()) ]</code> would <strong>not</strong> be an event since the times are decreasing.</li>
</ul></li>
</ul>

<p>Although we think of Events as lists, they are not implemented directly as them. Also, Events are abstract in that the representation itself isn&#8217;t manipulated directly. We&#8217;ll be using many Event functions that also apply to lists, and some that are specific to Events.</p>

<h2>Some simple examples</h2>

<p>Our examples are going to model various machines that have one button and a speaker that emits one sound. The button event is going to be of type <code>Event ()</code>. We&#8217;re using the () type since these events don&#8217;t carry any extra information, unlike a keypress event. Our sound event is going to be similarly represented as <code>Event ()</code>. So, quite simply our machines are all going to have the following type:
<!-- Think about doing type synonyms. type Button = (); type Bell = (). Beelsebob's suggestion --></p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">type</span> BellMachine <span style="color: #339933; font-weight: bold;">=</span> Event <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-</span>&amp;gt; Event <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span></pre></div></div>


<p>For our first example, lets implement a simple machine that emits the bell event whenever the button event occurs.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">doorBell <span style="color: #339933; font-weight: bold;">::</span> BellMachine
doorBell <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">id</span></pre></div></div>


<p>Using reactive, we can implement machines much more complex than a doorbell while retaining the same high-level of simplicity demonstrated in the above code.</p>

<p>Consider another simple machine. This one sounds a bell 3 minutes after it is turned on. Before we implement it, lets take a look at what functions Reactive includes for generating new events:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #5d478b; font-style: italic;">-- Converts a list of time/value pairs into an event. Note that the times _must_ be non-decreasing.</span>
listE <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span>TimeT<span style="color: #339933; font-weight: bold;">,</span>a<span style="color: green;">&#41;</span><span style="color: green;">&#93;</span> <span style="color: #339933; font-weight: bold;">-</span>&amp;gt; Event a
atTimes <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#91;</span>TimeT<span style="color: green;">&#93;</span> <span style="color: #339933; font-weight: bold;">-</span>&amp;gt; Event <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
atTime <span style="color: #339933; font-weight: bold;">::</span> TimeT <span style="color: #339933; font-weight: bold;">-</span>&amp;gt; Event <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span></pre></div></div>


<p>Assuming that time 0 is when the machine turns on, the bell event could be implemented like this:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #5d478b; font-style: italic;">-- Convert minutes to seconds</span>
mToS <span style="color: #339933; font-weight: bold;">::</span> <span style="color: #cccc00; font-weight: bold;">Double</span> <span style="color: #339933; font-weight: bold;">-</span>&amp;gt; <span style="color: #cccc00; font-weight: bold;">Double</span>
mToS <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">*</span><span style="color: green;">&#41;</span> <span style="color: red;">60</span>
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- The appropriate time to cook a soft-boiled egg is 3 minutes (see wikipedia)</span>
eggTimer <span style="color: #339933; font-weight: bold;">::</span> Event <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
eggTimer <span style="color: #339933; font-weight: bold;">=</span> atTime <span style="color: green;">&#40;</span>mToS <span style="color: red;">3</span><span style="color: green;">&#41;</span></pre></div></div>


<p>Note that <code>eggTimer</code> isn&#8217;t a machine of our initial type; It lacks any mention of an attached button. We make it into a machine of the appropriate type by ignoring all button presses using <code>const</code>.</p>

<!-- New name: eggTimer10Second? Maybe it could introduce another function that creates an eggTimer with a given delay. Bob -->


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">eggTimerM <span style="color: #339933; font-weight: bold;">::</span> BellMachine
eggTimerM <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">const</span> eggTimer
<span style="color: #5d478b; font-style: italic;">-- Alternative Definition</span>
<span style="color: #5d478b; font-style: italic;">-- eggTimerM = pure eggTimer</span></pre></div></div>


<h2>mempty/mappend (Monoid)</h2>

<p>Lets look at a machine that sounds the bell at 10 seconds <strong>and</strong> when the user presses the button. Reflect, for a moment, on how this would be implemented imperatively. Timers? Signals? Event Loops? Compare that sketch to the simplicity of, and code-reuse within, the following reactive definition.</p>

<!--
Bob suggested we do a double doorbell that rings when pressed and a little afterwards
doubleDoorbell b = b `mappend` delayE 0.5 b
It would be a more useful function. Also, this delayE could either be in reactive or we could say 'I'll show you how to define this later'. See notes in implementation
-->


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">nifty <span style="color: #339933; font-weight: bold;">::</span> BellMachine
nifty button <span style="color: #339933; font-weight: bold;">=</span> eggTimer `mappend` button
<span style="color: #5d478b; font-style: italic;">-- alternate definition</span>
<span style="color: #5d478b; font-style: italic;">-- nifty = mappend eggTimer</span></pre></div></div>


<p>We can think of <code>mappend</code> as merging events. Note that this function is part of the monoid concept and that <code>mempty</code>, <code>mappend</code>&#8217;s counterpart, represents an event that never occurs. Taking this into consideration, we can implement a completely silent machine like this:
<!-- Bob thinks that this could come before bell10s --></p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">silent <span style="color: #339933; font-weight: bold;">::</span> BellMachine
silent <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">const</span> mempty
<span style="color: #5d478b; font-style: italic;">-- Alternative Definition</span>
<span style="color: #5d478b; font-style: italic;">-- silent = pure mempty</span></pre></div></div>


<p>(Note: To use mappend and mempty, you&#8217;ll need to import Data.Monoid)</p>

<h2>A more difficult example (fmap/switchE) (Functor/Monad)</h2>

<p>Now lets implement a tricky machine. When the user presses the button twice, the machine begins pulsing the bell with a period equivalent to the time between the button presses. Another press of the button will stop the ringing at which point the process may be repeated.</p>

<p>Lets try to break the implementation into pieces. We know that we&#8217;ll need to calculate the difference of time between two event occurrences. For this sub-problem we&#8217;ll combine two of reactive&#8217;s functions, the first being <code>withTimeE</code></p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #5d478b; font-style: italic;">-- Combine an event instance's data with its corresponding time.</span>
withTimeE <span style="color: #339933; font-weight: bold;">::</span>  Event a <span style="color: #339933; font-weight: bold;">-</span>&amp;gt; Event <span style="color: green;">&#40;</span>a<span style="color: #339933; font-weight: bold;">,</span> TimeT<span style="color: green;">&#41;</span></pre></div></div>


<p><code>withTimeE</code> is typical of reactive&#8217;s built-in functions in that it carries along the input Event&#8217;s data in the first element of the resultant tuple, while the computed value gets inserted into the second element of the tuple. If we instead wanted to ignore the initial event&#8217;s data, we could define a new function, <code>withTimeE_</code>, as follows:</p>

<!-- Bob suggests we expand alt. def. to alternative definition every time -->


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">withTimeE<span style="color: #339933; font-weight: bold;">_</span> <span style="color: #339933; font-weight: bold;">::</span> Event a <span style="color: #339933; font-weight: bold;">-</span>&amp;gt; Event TimeT
withTimeE<span style="color: #339933; font-weight: bold;">_</span> e <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">fmap</span> <span style="font-weight: bold;">snd</span> <span style="color: green;">&#40;</span>withTimeE e<span style="color: green;">&#41;</span>
<span style="color: #5d478b; font-style: italic;">-- Alternative definition</span>
<span style="color: #5d478b; font-style: italic;">-- withTimeE_ = (fmap.fmap) snd withTimeE</span></pre></div></div>


<p><code>fmap</code> allows us to apply a function to all the values of an event. <code>fmap</code>, like <code>mappend/mempty</code>, works similarly on other data types including functions (see the Functor class defined in Control.Monad).</p>

<p>The function we&#8217;ll be using in conjunction with <code>withTimeE</code> is <code>withPrevE</code>. <code>withPrevE</code> couples each value in an event with the previous occurrence&#8217;s value.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">withPrevE <span style="color: #339933; font-weight: bold;">::</span>  Event a <span style="color: #339933; font-weight: bold;">-</span>&amp;gt; Event <span style="color: green;">&#40;</span>a<span style="color: #339933; font-weight: bold;">,</span> a<span style="color: green;">&#41;</span></pre></div></div>


<p>Similar to <code>withTimeE</code>, it adds the computed value (in this case, the <em>previous</em> value) to the <code>snd</code> part of the tuple.</p>

<p>Combining these two functions, we can transform an <code>Event ()</code> into an <code>Event TimeT</code> that represents the time passed since the previous event.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">elapsedFirstTry <span style="color: #339933; font-weight: bold;">::</span> Event <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-</span>&amp;gt; Event TimeT
elapsedFirstTry e <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">fmap</span> f <span style="color: green;">&#40;</span>withPrevE <span style="color: green;">&#40;</span>withTimeE<span style="color: #339933; font-weight: bold;">_</span> e<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
  <span style="color: #06c; font-weight: bold;">where</span>
    f <span style="color: green;">&#40;</span>tCur<span style="color: #339933; font-weight: bold;">,</span> tPrev<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> tCur <span style="color: #339933; font-weight: bold;">-</span> tPrev
<span style="color: #5d478b; font-style: italic;">-- alt. def.</span>
<span style="color: #5d478b; font-style: italic;">-- elapsedFirstTry = fmap (uncurry (-)) . withPrevE . withTimeE_</span></pre></div></div>


<p>The above definition is all right, but in the spirit of reactive&#8217;s composability, we&#8217;ll define a more generally useful version that carries along the input event&#8217;s data and one that ignores it.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">withElapsed <span style="color: #339933; font-weight: bold;">::</span> Event a <span style="color: #339933; font-weight: bold;">-</span>&amp;gt; Event <span style="color: green;">&#40;</span>a<span style="color: #339933; font-weight: bold;">,</span> TimeT<span style="color: green;">&#41;</span>
withElapsed <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">fmap</span> f <span style="color: #339933; font-weight: bold;">.</span> withPrevE <span style="color: #339933; font-weight: bold;">.</span> withTimeE
  <span style="color: #06c; font-weight: bold;">where</span>
    f <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>aCur<span style="color: #339933; font-weight: bold;">,</span> tCur<span style="color: green;">&#41;</span><span style="color: #339933; font-weight: bold;">,</span> <span style="color: green;">&#40;</span>aPrev<span style="color: #339933; font-weight: bold;">,</span> tPrev<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span>aCur<span style="color: #339933; font-weight: bold;">,</span> tCur<span style="color: #339933; font-weight: bold;">-</span>tPrev<span style="color: green;">&#41;</span>
&nbsp;
withElapsed<span style="color: #339933; font-weight: bold;">_</span> <span style="color: #339933; font-weight: bold;">::</span> Event a <span style="color: #339933; font-weight: bold;">-</span>&amp;gt; Event TimeT
withElapsed<span style="color: #339933; font-weight: bold;">_</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span><span style="font-weight: bold;">fmap</span><span style="color: #339933; font-weight: bold;">.</span><span style="font-weight: bold;">fmap</span><span style="color: green;">&#41;</span> <span style="font-weight: bold;">snd</span> withElapsed</pre></div></div>


<p><code>withElapsed</code> gets is pretty far along the way of implementing the proposed machine, but we still have a ways to go. Observe that we only care about the elapsed time every 3rd time the button is pressed. To ease identification of these particular presses, we&#8217;ll label the event occurrences with a state. First, we&#8217;ll define our state data type and a method to cycle them.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">data</span> State <span style="color: #339933; font-weight: bold;">=</span> Idle
           | WaitingForPeriodEnd
           | PlayingCycle
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- Given a state returns the next in sequence</span>
next <span style="color: #339933; font-weight: bold;">::</span> State <span style="color: #339933; font-weight: bold;">-</span>&amp;gt; State
next Idle                <span style="color: #339933; font-weight: bold;">=</span> WaitingForPeriodEnd
next WaitingForPeriodEnd <span style="color: #339933; font-weight: bold;">=</span> PlayingCycle
next PlayingCycle        <span style="color: #339933; font-weight: bold;">=</span> Idle</pre></div></div>


<p>Reactive includes a simple function that will do the Event labeling for us.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #5d478b; font-style: italic;">-- | State machine, given initial value and transition function.  Carries</span>
<span style="color: #5d478b; font-style: italic;">-- along event data.</span>
mealy <span style="color: #339933; font-weight: bold;">::</span> s <span style="color: #339933; font-weight: bold;">-</span>&amp;gt; <span style="color: green;">&#40;</span>s <span style="color: #339933; font-weight: bold;">-</span>&amp;gt; s<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-</span>&amp;gt; Event b <span style="color: #339933; font-weight: bold;">-</span>&amp;gt; Event <span style="color: green;">&#40;</span>b<span style="color: #339933; font-weight: bold;">,</span>s<span style="color: green;">&#41;</span>
mealy<span style="color: #339933; font-weight: bold;">_</span> <span style="color: #339933; font-weight: bold;">::</span> s <span style="color: #339933; font-weight: bold;">-</span>&amp;gt; <span style="color: green;">&#40;</span>s <span style="color: #339933; font-weight: bold;">-</span>&amp;gt; s<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-</span>&amp;gt; Event b <span style="color: #339933; font-weight: bold;">-</span>&amp;gt; Event s</pre></div></div>


<p>Here is what we have so far . . . we&#8217;re getting pretty close.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">soFar <span style="color: #339933; font-weight: bold;">::</span>  Event <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-</span>&amp;gt; Event <span style="color: green;">&#40;</span>TimeT<span style="color: #339933; font-weight: bold;">,</span> State<span style="color: green;">&#41;</span>
soFar <span style="color: #339933; font-weight: bold;">=</span> mealy Idle next <span style="color: #339933; font-weight: bold;">.</span> withElapsed<span style="color: #339933; font-weight: bold;">_</span></pre></div></div>


<p>How do we generate the pulse events for the <code>PlayingCycle</code> state? For this type of situation, reactive has a few functions that have the signature <code>Event (Event a) -&gt; Event a</code>. The most general of these is called join which applies to all Monads. In our case we&#8217;ll be using the <code>switchE.</code></p>

<p><code></p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #5d478b; font-style: italic;">-- | Switch from one event to another, as they occur.</span>
switchE <span style="color: #339933; font-weight: bold;">::</span> Event <span style="color: green;">&#40;</span>Event a<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-</span>&amp;gt; Event a</pre></div></div>


<p>To use <code>switchE</code> we&#8217;ll need to fmap our Event (TimeT, State) into an Event (Event ()). But first, lets define a function that will generate our periodic alarms:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">period <span style="color: #339933; font-weight: bold;">::</span> TimeT <span style="color: #339933; font-weight: bold;">-</span>&amp;gt; TimeT <span style="color: #339933; font-weight: bold;">-</span>&amp;gt; Event <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
period delta t0 <span style="color: #339933; font-weight: bold;">=</span> atTimes <span style="color: green;">&#40;</span><span style="font-weight: bold;">iterate</span> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">+</span><span style="color: green;">&#41;</span> delta<span style="color: green;">&#41;</span> t0<span style="color: green;">&#41;</span></pre></div></div>


<p>And now we put it all together:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">metronome <span style="color: #339933; font-weight: bold;">::</span> BellMachine
metronome <span style="color: #339933; font-weight: bold;">=</span> switchE <span style="color: #339933; font-weight: bold;">.</span> <span style="font-weight: bold;">fmap</span> f <span style="color: #339933; font-weight: bold;">.</span> withTimeE <span style="color: #339933; font-weight: bold;">.</span> mealy Idle next <span style="color: #339933; font-weight: bold;">.</span> withElapsed<span style="color: #339933; font-weight: bold;">_</span>
  <span style="color: #06c; font-weight: bold;">where</span>
    f <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>dt<span style="color: #339933; font-weight: bold;">,</span>PlayingCycle<span style="color: green;">&#41;</span><span style="color: #339933; font-weight: bold;">,</span> t<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> period dt t
    f <span style="color: #339933; font-weight: bold;">_</span> <span style="color: #339933; font-weight: bold;">=</span> mempty</pre></div></div>


<h2>More to come</h2>

<p>Our examples using Events are just the tip of the iceberg of reactive&#8217;s potential. In the next article, I&#8217;ll be explaining reactive&#8217;s Behaviors, which can be <em>thought of</em> as functions of time.</p>

<p><a href="http://netsuperbrain.com/blog/posts/introducing-reactive-behaviors">continue on</a>&#8230;</p>

<h2>Acknowledgments</h2>

<p>This tutorial was created by David Sankel and <a href="http://conal.net">Conal Elliott</a> with important input from Thomas Davie and was sponsored by <a href="http://www.anygma.com">Anygma</a>
<!-- See http://wiki.anygma.com/index.php/Image:Wiper.png --></p>

<p></code></p>
]]></content:encoded>
			<wfw:commentRss>http://netsuperbrain.com/blog/posts/introducing-reactive-events/feed/</wfw:commentRss>
		</item>
		<item>
		<title>freeglut + Windows + HOpenGL + HGLUT</title>
		<link>http://netsuperbrain.com/blog/posts/freeglut-windows-hopengl-hglut/</link>
		<comments>http://netsuperbrain.com/blog/posts/freeglut-windows-hopengl-hglut/#comments</comments>
		<pubDate>Thu, 06 Nov 2008 21:10:46 +0000</pubDate>
		<dc:creator>David Sankel</dc:creator>
		
		<category><![CDATA[Haskell]]></category>

		<category><![CDATA[FreeGLUT]]></category>

		<category><![CDATA[OpenGL]]></category>

		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://netsuperbrain.com/blog/?p=136</guid>
		<description><![CDATA[freeglut is a version of glut that is vastly superior to the one typically used with windows. Aside from being Open Source, it interacts well with ghci (see leaveMainLoop) and provides a rhombic dodecahedron primitive. This post walks through the somewhat complicated process of getting Freeglut and the haskell OpenGL and GLUT bindings installed and [...]]]></description>
			<content:encoded><![CDATA[<p>freeglut is a version of glut that is vastly superior to the one typically used with windows. Aside from being Open Source, it interacts well with ghci (see leaveMainLoop) and provides a rhombic dodecahedron primitive. This post walks through the somewhat complicated process of getting Freeglut and the haskell OpenGL and GLUT bindings installed and working on windows. This feat is accomplished using the brand new ghc 6.10.1.
<span id="more-136"></span></p>

<h2>Install mingw &amp; msys</h2>

<p>Mingw and msys are required for the compiler and configure scripts. It has been reported to me that cygwin, which provides similar functionality, will <em>not</em> work.</p>

<p><strong>MinGW</strong>. First, download the <a href="http://downloads.sourceforge.net/mingw/MinGW-5.1.4.exe?modtime=1209244789&amp;big_mirror=1">MinGW 5.1.4 installer</a> and save it in a new folder. Execute the file and, when prompted, choose a minimal installation (it is important that you don&#8217;t install MinGW make).</p>

<p><strong>MSYS</strong>. Download and run the <a href="http://downloads.sourceforge.net/mingw/MSYS-1.0.10.exe?modtime=1079444447&amp;big_mirror=1">msys 1.0.10 installer</a>. You&#8217;ll be prompted with a console. Say yes to post install, reply yes to having MinGW installed, and type in your mingw location (default is C:/MinGW).</p>

<p>To check everything installed correctly, use Start-&gt;Programs-&gt;MinGW-&gt;MSYS-&gt;msys to open a prompt. At the prompt, typing <code>gcc --version</code> should show you the version of gcc you have installed.</p>

<h2>Compile and Install freeglut</h2>

<p>Download <a href="http://superb-east.dl.sourceforge.net/sourceforge/freeglut/freeglut-2.4.0.tar.gz">freeglut 2.4.0 source distribution</a> and save it to <code>C:\msys\1.0\home\&lt;Your Username&gt;</code> (This is your default msys home directory. If you have your HOME environment variable set for another program, like emacs, your msys home directory is the value of that variable.).</p>

<p>Start the msys window, if you don&#8217;t already have one opened, and type the following commands at the prompt. You can paste into the msys window using SHIFT+INSERT or middle click.:</p>


<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">tar</span> <span style="color: #660033;">-zxf</span> freeglut-2.4.0.tar.gz
<span style="color: #7a0874; font-weight: bold;">cd</span> freeglut-2.4.0<span style="color: #000000; font-weight: bold;">/</span>src<span style="color: #000000; font-weight: bold;">/</span>
<span style="color: #c20cb9; font-weight: bold;">gcc</span> <span style="color: #660033;">-O2</span> <span style="color: #660033;">-c</span> -DFREEGLUT_EXPORTS <span style="color: #000000; font-weight: bold;">*</span>.c -I..<span style="color: #000000; font-weight: bold;">/</span>include
<span style="color: #c20cb9; font-weight: bold;">gcc</span> <span style="color: #660033;">-shared</span> <span style="color: #660033;">-o</span> glut32.dll <span style="color: #000000; font-weight: bold;">*</span>.o -Wl,--enable-stdcall-fixup,--out-implib,libglut32.a <span style="color: #660033;">-lopengl32</span> <span style="color: #660033;">-lglu32</span> <span style="color: #660033;">-lgdi32</span> <span style="color: #660033;">-lwinmm</span></pre></div></div>


<p>Now you should be left with glut32.dll and libglut32.a in that directory. Now move glut32.dll into your windows system32 directory.</p>


<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">cp</span> glut32.dll <span style="color: #000000; font-weight: bold;">/</span>c<span style="color: #000000; font-weight: bold;">/</span>WINDOWS<span style="color: #000000; font-weight: bold;">/</span>system32</pre></div></div>


<p>libglut32.a needs to be copied to ghc&#8217;s gcc-lib directory.</p>


<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">cp</span> libglut32.a <span style="color: #000000; font-weight: bold;">/</span>c<span style="color: #000000; font-weight: bold;">/</span>ghc<span style="color: #000000; font-weight: bold;">/</span>ghc-6.10.1<span style="color: #000000; font-weight: bold;">/</span>gcc-lib<span style="color: #000000; font-weight: bold;">/</span></pre></div></div>


<h2>Haskell OpenGL Binding</h2>

<p>Download the haskell OpenGL binding from hackage <a href="http://hackage.haskell.org/cgi-bin/hackage-scripts/package/OpenGL">here</a>. At the time of this writing, the latest version was 2.2.1.1. Save it to your msys home directory, then type:</p>


<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">tar</span> <span style="color: #660033;">-zxf</span> OpenGL-2.2.1.1.tar.gz
<span style="color: #7a0874; font-weight: bold;">cd</span> OpenGL-2.2.1.1
runhaskell Setup configure
runhaskell Setup build
runhaskell Setup <span style="color: #c20cb9; font-weight: bold;">install</span></pre></div></div>


<h2>Haskell GLUT Binding</h2>

<p>Download the haskell GLUT binding from hackage <a href="http://hackage.haskell.org/cgi-bin/hackage-scripts/package/GLUT">here</a>. At the time of this writing, the latest version was 2.1.1.2. Save it to your msys home directory.</p>

<p>You&#8217;ll also need to download the glutwin2112 patch (<a href='http://netsuperbrain.com/blog/wp-content/uploads/2008/11/glutwin2112.patch'>glutwin2112.patch</a>) and save this to the msys home directory.</p>

<p>Then from an msys prompt enter the following:</p>


<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">tar</span> <span style="color: #660033;">-zxf</span> GLUT-2.1.1.2.tar.gz
<span style="color: #7a0874; font-weight: bold;">cd</span> GLUT-2.1.1.2
<span style="color: #c20cb9; font-weight: bold;">patch</span> <span style="color: #660033;">-p1</span> <span style="color: #000000; font-weight: bold;">&lt;</span> ..<span style="color: #000000; font-weight: bold;">/</span>glutWin2112.patch
<span style="color: #007800;">C_INCLUDE_PATH</span>=<span style="color: #ff0000;">&quot;../freeglut-2.4.0/include/&quot;</span> <span style="color: #007800;">LIBRARY_PATH</span>=<span style="color: #ff0000;">&quot;../freeglut-2.4.0/src/&quot;</span> runhaskell Setup configure
<span style="color: #007800;">C_INCLUDE_PATH</span>=<span style="color: #ff0000;">&quot;../freeglut-2.4.0/include/&quot;</span> <span style="color: #007800;">LIBRARY_PATH</span>=<span style="color: #ff0000;">&quot;../freeglut-2.4.0/src/&quot;</span> runhaskell Setup build
<span style="color: #007800;">C_INCLUDE_PATH</span>=<span style="color: #ff0000;">&quot;../freeglut-2.4.0/include/&quot;</span> <span style="color: #007800;">LIBRARY_PATH</span>=<span style="color: #ff0000;">&quot;../freeglut-2.4.0/src/&quot;</span> runhaskell Setup <span style="color: #c20cb9; font-weight: bold;">install</span></pre></div></div>


<h2>Testing</h2>

<p>Try to save and run the following file (<a href='http://netsuperbrain.com/blog/wp-content/uploads/2008/11/teapots.hs'>teapots.hs</a>). You should see a shaded sphere when run.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #5d478b; font-style: italic;">{-
   Light.hs (adapted from light.c which is (c) Silicon Graphics, Inc.)
   Copyright (c) Sven Panne 2002-2005 &lt;sven.panne@aedion.de&gt;
   This file is part of HOpenGL and distributed under a BSD-style license
   See the file libraries/GLUT/LICENSE
&nbsp;
   This program demonstrates the use of the OpenGL lighting model. A sphere
   is drawn using a grey material characteristic. A single light source
   illuminates the object.
-}</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">import</span> System<span style="color: #339933; font-weight: bold;">.</span>Exit <span style="color: green;">&#40;</span> exitWith<span style="color: #339933; font-weight: bold;">,</span> ExitCode<span style="color: green;">&#40;</span>ExitSuccess<span style="color: green;">&#41;</span> <span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">import</span> Graphics<span style="color: #339933; font-weight: bold;">.</span>UI<span style="color: #339933; font-weight: bold;">.</span>GLUT
&nbsp;
myInit <span style="color: #339933; font-weight: bold;">::</span> <span style="color: #cccc00; font-weight: bold;">IO</span> <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
myInit <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #06c; font-weight: bold;">do</span>
   clearColor <span style="color: #339933; font-weight: bold;">$=</span> Color4 0 0 0 0
   shadeModel <span style="color: #339933; font-weight: bold;">$=</span> Smooth
&nbsp;
   materialSpecular Front <span style="color: #339933; font-weight: bold;">$=</span> Color4 <span style="color: red;">1</span> <span style="color: red;">1</span> <span style="color: red;">1</span> <span style="color: red;">1</span>
   materialShininess Front <span style="color: #339933; font-weight: bold;">$=</span> <span style="color: red;">50</span>
   position <span style="color: green;">&#40;</span>Light 0<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">$=</span> Vertex4 <span style="color: red;">1</span> <span style="color: red;">1</span> <span style="color: red;">1</span> 0
&nbsp;
   lighting <span style="color: #339933; font-weight: bold;">$=</span> Enabled
   light <span style="color: green;">&#40;</span>Light 0<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">$=</span> Enabled
   depthFunc <span style="color: #339933; font-weight: bold;">$=</span> Just Less
&nbsp;
display <span style="color: #339933; font-weight: bold;">::</span> DisplayCallback
display <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #06c; font-weight: bold;">do</span>
   clear <span style="color: green;">&#91;</span> ColorBuffer<span style="color: #339933; font-weight: bold;">,</span> DepthBuffer <span style="color: green;">&#93;</span>
   renderObject Solid <span style="color: green;">&#40;</span>Sphere' <span style="color: red;">1</span> <span style="color: red;">20</span> <span style="color: red;">16</span><span style="color: green;">&#41;</span>
   flush
&nbsp;
reshape <span style="color: #339933; font-weight: bold;">::</span> ReshapeCallback
reshape size<span style="color: #339933; font-weight: bold;">@</span><span style="color: green;">&#40;</span>Size w h<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #06c; font-weight: bold;">do</span>
   viewport <span style="color: #339933; font-weight: bold;">$=</span> <span style="color: green;">&#40;</span>Position 0 0<span style="color: #339933; font-weight: bold;">,</span> size<span style="color: green;">&#41;</span>
   matrixMode <span style="color: #339933; font-weight: bold;">$=</span> Projection
   loadIdentity
   <span style="color: #06c; font-weight: bold;">let</span> wf <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">fromIntegral</span> w
       hf <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">fromIntegral</span> h
   <span style="color: #06c; font-weight: bold;">if</span> w <span style="color: #339933; font-weight: bold;">&lt;=</span> h
      <span style="color: #06c; font-weight: bold;">then</span> ortho <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">-</span><span style="color: red;">1.5</span><span style="color: green;">&#41;</span> <span style="color: red;">1.5</span> <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">-</span><span style="color: red;">1.5</span> <span style="color: #339933; font-weight: bold;">*</span> hf<span style="color: #339933; font-weight: bold;">/</span>wf<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span><span style="color: red;">1.5</span> <span style="color: #339933; font-weight: bold;">*</span> hf<span style="color: #339933; font-weight: bold;">/</span>wf<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">-</span><span style="color: red;">10</span><span style="color: green;">&#41;</span> <span style="color: red;">10</span>
      <span style="color: #06c; font-weight: bold;">else</span> ortho <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">-</span><span style="color: red;">1.5</span> <span style="color: #339933; font-weight: bold;">*</span> wf<span style="color: #339933; font-weight: bold;">/</span>hf<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span><span style="color: red;">1.5</span> <span style="color: #339933; font-weight: bold;">*</span> wf<span style="color: #339933; font-weight: bold;">/</span>hf<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">-</span><span style="color: red;">1.5</span><span style="color: green;">&#41;</span> <span style="color: red;">1.5</span> <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">-</span><span style="color: red;">10</span><span style="color: green;">&#41;</span> <span style="color: red;">10</span>
   matrixMode <span style="color: #339933; font-weight: bold;">$=</span> Modelview 0
   loadIdentity
&nbsp;
keyboard <span style="color: #339933; font-weight: bold;">::</span> KeyboardMouseCallback
keyboard <span style="color: green;">&#40;</span><span style="color: #cccc00; font-weight: bold;">Char</span> '\<span style="color: red;">27</span>'<span style="color: green;">&#41;</span> Down <span style="color: #339933; font-weight: bold;">_</span> <span style="color: #339933; font-weight: bold;">_</span> <span style="color: #339933; font-weight: bold;">=</span> exitWith ExitSuccess
keyboard <span style="color: #339933; font-weight: bold;">_</span>            <span style="color: #339933; font-weight: bold;">_</span>    <span style="color: #339933; font-weight: bold;">_</span> <span style="color: #339933; font-weight: bold;">_</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">return</span> <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
&nbsp;
main <span style="color: #339933; font-weight: bold;">::</span> <span style="color: #cccc00; font-weight: bold;">IO</span> <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
main <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #06c; font-weight: bold;">do</span>
   <span style="color: green;">&#40;</span>progName<span style="color: #339933; font-weight: bold;">,</span> <span style="color: #339933; font-weight: bold;">_</span>args<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">&lt;-</span> getArgsAndInitialize
   initialDisplayMode <span style="color: #339933; font-weight: bold;">$=</span> <span style="color: green;">&#91;</span> SingleBuffered<span style="color: #339933; font-weight: bold;">,</span> RGBMode<span style="color: #339933; font-weight: bold;">,</span> WithDepthBuffer <span style="color: green;">&#93;</span>
   initialWindowSize <span style="color: #339933; font-weight: bold;">$=</span> Size <span style="color: red;">500</span> <span style="color: red;">500</span>
   initialWindowPosition <span style="color: #339933; font-weight: bold;">$=</span> Position <span style="color: red;">100</span> <span style="color: red;">100</span>
   createWindow progName
   myInit
   displayCallback <span style="color: #339933; font-weight: bold;">$=</span> display
   reshapeCallback <span style="color: #339933; font-weight: bold;">$=</span> Just reshape
   keyboardMouseCallback <span style="color: #339933; font-weight: bold;">$=</span> Just keyboard
   mainLoop</pre></div></div>


<h2>Troubleshooting</h2>

<p><b>Linker Errors</b>. Pay close attention to the output of the GLUT configure command, it should have a line that looks like:</p>

<p><pre>
checking for GLUT library... -lglut32 -lglu32 -lopengl32 
</pre></p>

<p>If not, it may have failed without telling you so.</p>

<p><b>More Resources</b>. The haskell-cafe mailing list is a good place to ask for help. Also <a href="http://joelhough.com/blog/2008/04/14/haskell-and-freeglut-at-last/">this site</a> has some information on getting freeglut+windows working with an older version of ghc.</p>

<h2>Acknowledgments</h2>

<p><a href="http://joelhough.com">joelhough.com</a> blog for getting me started. Peter Verswyvelen for information on the HOME variable and pasting into the msys window. RayNBow for noting that the libglut32.a must be copied to a ghc directory. newsham and Greg Fitzgerald for noting the issues prompting the need for a patch. And all others who I may have forgotten.</p>
]]></content:encoded>
			<wfw:commentRss>http://netsuperbrain.com/blog/posts/freeglut-windows-hopengl-hglut/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Analysis of lazy-stream programs.</title>
		<link>http://netsuperbrain.com/blog/posts/analysis-of-lazy-stream-programs/</link>
		<comments>http://netsuperbrain.com/blog/posts/analysis-of-lazy-stream-programs/#comments</comments>
		<pubDate>Thu, 23 Oct 2008 15:33:45 +0000</pubDate>
		<dc:creator>David Sankel</dc:creator>
		
		<category><![CDATA[Haskell]]></category>

		<guid isPermaLink="false">http://netsuperbrain.com/blog/?p=74</guid>
		<description><![CDATA[What&#8217;s the difference between the following two functions, a and b:


import Control.Monad.Instances
import Control.Arrow
&#160;
a, b :: &#40;Int-&#62;Int&#41; -&#62; &#40;Int,Int&#41; -&#62; &#40;Int,Int&#41;
a = fmap
b = second


Can you figure it out?  If not, here&#8217;s a hint


f ::  &#40;&#40;Int -&#62; Int&#41; -&#62; Int -&#62; &#40;Int, Int&#41;&#41; -&#62; Int -&#62; Int
f sec a = case sec &#40;+1&#41; a [...]]]></description>
			<content:encoded><![CDATA[<p>What&#8217;s the difference between the following two functions, a and b:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">import</span> Control<span style="color: #339933; font-weight: bold;">.</span><span style="color: #cccc00; font-weight: bold;">Monad</span><span style="color: #339933; font-weight: bold;">.</span>Instances
<span style="color: #06c; font-weight: bold;">import</span> Control<span style="color: #339933; font-weight: bold;">.</span>Arrow
&nbsp;
a<span style="color: #339933; font-weight: bold;">,</span> b <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#40;</span>Int<span style="color: #339933; font-weight: bold;">-&gt;</span>Int<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#40;</span><span style="color: #cccc00; font-weight: bold;">Int</span><span style="color: #339933; font-weight: bold;">,</span><span style="color: #cccc00; font-weight: bold;">Int</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#40;</span><span style="color: #cccc00; font-weight: bold;">Int</span><span style="color: #339933; font-weight: bold;">,</span><span style="color: #cccc00; font-weight: bold;">Int</span><span style="color: green;">&#41;</span>
a <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">fmap</span>
b <span style="color: #339933; font-weight: bold;">=</span> second</pre></div></div>


<p>Can you figure it out? <span id="more-74"></span> If not, here&#8217;s a hint</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">f <span style="color: #339933; font-weight: bold;">::</span>  <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span><span style="color: #cccc00; font-weight: bold;">Int</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">Int</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">Int</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#40;</span><span style="color: #cccc00; font-weight: bold;">Int</span><span style="color: #339933; font-weight: bold;">,</span> <span style="color: #cccc00; font-weight: bold;">Int</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">Int</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">Int</span>
f sec a <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #06c; font-weight: bold;">case</span> sec <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">+</span><span style="color: red;">1</span><span style="color: green;">&#41;</span> a <span style="color: #06c; font-weight: bold;">of</span> <span style="color: green;">&#40;</span>x<span style="color: #339933; font-weight: bold;">,</span>y<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: red;">6</span></pre></div></div>


<p>The two functions, a and b, are identical for every single input, except one. Did you figure it out?</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #339933; font-weight: bold;">*</span>Main<span style="color: #339933; font-weight: bold;">&gt;</span> f a <span style="font-weight: bold;">undefined</span>
<span style="color: #339933; font-weight: bold;">***</span> Exception: <span style="color: #06c; font-weight: bold;">Prelude</span><span style="color: #339933; font-weight: bold;">.</span><span style="font-weight: bold;">undefined</span>
<span style="color: #339933; font-weight: bold;">*</span>Main<span style="color: #339933; font-weight: bold;">&gt;</span> f b <span style="font-weight: bold;">undefined</span>
<span style="color: red;">6</span></pre></div></div>


<p>Undefined, also called bottom or <img src="http://netsuperbrain.com/blog/wp-content/cache/tex_7814a0e7fffecda9cebb60d2bc160257.png" align="absmiddle" class="tex" alt="\bot" />, is a subtle value in lazy languages like haskell and for certain types of programs, this can make a big difference. The functions <code>a</code> and <code>b</code> apply to <img src="http://netsuperbrain.com/blog/wp-content/cache/tex_7814a0e7fffecda9cebb60d2bc160257.png" align="absmiddle" class="tex" alt="\bot" /> as follows:</p>

<p><center><img src="http://netsuperbrain.com/blog/wp-content/cache/tex_b5ee767f3e549b29069fb3416d3d7797.png" align="absmiddle" class="tex" alt="a f \bot \Rightarrow \bot" /></center>
<center><img src="http://netsuperbrain.com/blog/wp-content/cache/tex_74b7906cb1b9d3389317f35920e0313e.png" align="absmiddle" class="tex" alt="b f \bot \Rightarrow (\bot,\bot)" /></center></p>

<p>We say a function <img src="http://netsuperbrain.com/blog/wp-content/cache/tex_8fa14cdd754f91cc6554c9e71929cce7.png" align="absmiddle" class="tex" alt="f" /> is strict if <img src="http://netsuperbrain.com/blog/wp-content/cache/tex_6cc43f15911d69b13397b9f970ad73de.png" align="absmiddle" class="tex" alt="f \bot \Rightarrow \bot" /> and is non-strict otherwise. Looking at the definition of fmap for tuples, we can see why it is strict in its second argument:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">instance</span> <span style="color: #cccc00; font-weight: bold;">Functor</span> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">,</span><span style="color: green;">&#41;</span> a<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
	<span style="font-weight: bold;">fmap</span> f <span style="color: green;">&#40;</span>x<span style="color: #339933; font-weight: bold;">,</span>y<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span>x<span style="color: #339933; font-weight: bold;">,</span> f y<span style="color: green;">&#41;</span></pre></div></div>


<p>Before evaluation even gets to the right hand side of the equal sign, it will return <img src="http://netsuperbrain.com/blog/wp-content/cache/tex_b70979a357cfbe7c61e4c686ea2beb93.png" align="absmiddle" class="tex" alt="\perp" /> because it cannot pattern match (x,y) on <code>undefined</code>. We can make this non-strict in a couple ways, the first uses functions as an alternative to pattern matching:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">instance</span> <span style="color: #cccc00; font-weight: bold;">Functor</span> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">,</span><span style="color: green;">&#41;</span> a<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
	<span style="font-weight: bold;">fmap</span> f t <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span><span style="font-weight: bold;">fst</span> t<span style="color: #339933; font-weight: bold;">,</span> f <span style="color: green;">&#40;</span><span style="font-weight: bold;">snd</span> t<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre></div></div>


<p>The second uses the special tilde (~) symbol to delay the pattern matching until the result is actually used.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">instance</span> <span style="color: #cccc00; font-weight: bold;">Functor</span> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">,</span><span style="color: green;">&#41;</span> a<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
	<span style="font-weight: bold;">fmap</span> f <span style="color: #339933; font-weight: bold;">~</span><span style="color: green;">&#40;</span>x<span style="color: #339933; font-weight: bold;">,</span>y<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span>x<span style="color: #339933; font-weight: bold;">,</span> f y<span style="color: green;">&#41;</span></pre></div></div>


<p>And we see, the non-strict second function, is implemented as follows, using the tilde approach.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">instance</span> Arrow <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">-&gt;</span><span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
<span style="color: #5d478b; font-style: italic;">-- ...</span>
	first f <span style="color: #339933; font-weight: bold;">=</span> f <span style="color: #339933; font-weight: bold;">***</span> <span style="font-weight: bold;">id</span>
	second f <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">id</span> <span style="color: #339933; font-weight: bold;">***</span> f
	<span style="color: green;">&#40;</span>f <span style="color: #339933; font-weight: bold;">***</span> g<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">~</span><span style="color: green;">&#40;</span>x<span style="color: #339933; font-weight: bold;">,</span>y<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span>f x<span style="color: #339933; font-weight: bold;">,</span> g y<span style="color: green;">&#41;</span></pre></div></div>


<h2>Why non-strict?</h2>

<p>At first glance, it might seem silly to implement functions non-strictly. After all, the earlier these functions fail out with bottom, the more efficient the program is in these cases. However, one particular point of interest is lazy streams.</p>

<p>Recall that the <code>getContents :: IO [Char] </code> function returns a lazy list of input characters. Lets create a couple functions that motivate extra laziness.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">import</span> <span style="color: #cccc00; font-weight: bold;">IO</span>
&nbsp;
withNext <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#91;</span><span style="color: #cccc00; font-weight: bold;">Char</span><span style="color: green;">&#93;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="color: #cccc00; font-weight: bold;">Char</span><span style="color: #339933; font-weight: bold;">,</span><span style="color: #cccc00; font-weight: bold;">Char</span><span style="color: green;">&#41;</span><span style="color: green;">&#93;</span>
withNext <span style="color: green;">&#40;</span>a:a':<span style="color: #06c; font-weight: bold;">as</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span>a<span style="color: #339933; font-weight: bold;">,</span>a'<span style="color: green;">&#41;</span>:withNext <span style="color: green;">&#40;</span>a':<span style="color: #06c; font-weight: bold;">as</span><span style="color: green;">&#41;</span>
&nbsp;
main <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #06c; font-weight: bold;">do</span>
  hSetBuffering stdout NoBuffering
  hSetBuffering stdin NoBuffering
  <span style="font-weight: bold;">fmap</span> withNext <span style="font-weight: bold;">getContents</span> <span style="color: #339933; font-weight: bold;">&gt;&gt;=</span> <span style="font-weight: bold;">putStr</span> <span style="color: #339933; font-weight: bold;">.</span> <span style="font-weight: bold;">map</span> <span style="font-weight: bold;">fst</span></pre></div></div>


<p>When I run this program (sorry windows users, <a href="http://hackage.haskell.org/trac/ghc/ticket/2189">this won&#8217;t work for you</a>), and type &#8220;Hello World!&#8221;, here is what I get.</p>

<p><code></p>

<blockquote>
  <p>runhaskell test
  <u>He</u>H<u>l</u>e<u>l</u>l<u>o</u>l<u> </u>o<u>W</u> <u>o</u>W<u>r</u>o<u>l</u>r<u>d</u>l<u>!</u>d
  </code></p>
</blockquote>

<p>The underlined letters are the ones I typed. How did this happen? Note the following about <code>withNext</code>:</p>

<p><center><img src="http://netsuperbrain.com/blog/wp-content/cache/tex_ec3e35131e990ad80e9c2393e51045fc.png" align="absmiddle" class="tex" alt="\mbox{\bf withNext} (x:\bot) \Rightarrow \perp" /></center></p>

<p>It is strict in the second half of its argument. Lets modify our function to be more lazy in this respect.</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;">withNext' <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#91;</span><span style="color: #cccc00; font-weight: bold;">Char</span><span style="color: green;">&#93;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="color: #cccc00; font-weight: bold;">Char</span><span style="color: #339933; font-weight: bold;">,</span><span style="color: #cccc00; font-weight: bold;">Char</span><span style="color: green;">&#41;</span><span style="color: green;">&#93;</span>
withNext' <span style="color: green;">&#40;</span>a:<span style="color: #06c; font-weight: bold;">as</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span>a<span style="color: #339933; font-weight: bold;">,</span> <span style="font-weight: bold;">head</span> <span style="color: #06c; font-weight: bold;">as</span><span style="color: green;">&#41;</span>:withNext <span style="color: #06c; font-weight: bold;">as</span>
<span style="color: #5d478b; font-style: italic;">-- Or, the tilde version</span>
<span style="color: #5d478b; font-style: italic;">-- withNext' (a:(~(a':as))) = (a,a'):withNext (a':as)</span></pre></div></div>


<p>As was the case with <code>withNext</code>, <code>withNext'</code> is strict in its argument.</p>

<p><center><img src="http://netsuperbrain.com/blog/wp-content/cache/tex_17a7cc4a45028534a494996c3a2ee0e5.png" align="absmiddle" class="tex" alt="\mbox{\bf withNext' } \bot \Rightarrow \bot" /></center></p>

<p>Using this, we can see that <code>withNext'</code> is <strong>not</strong> strict in the second half of its argument.</p>

<p><center><img src="http://netsuperbrain.com/blog/wp-content/cache/tex_87fd1559e57d399260f446ff9177e673.png" align="absmiddle" class="tex" alt="\mbox{\bf withNext' } (x:\bot) \Rightarrow (x,\bot):\bot" /></center></p>

<p>When we run our more lazy version of this program, we get what we&#8217;d expect:</p>

<p><code></p>

<blockquote>
  <p>runhaskell test
  <u>H</u>H<u>e</u>e<u>l</u>l<u>l</u>l<u>o</u>o<u> </u> <u>W</u>W<u>o</u>o<u>r</u>r<u>l</u>l<u>d</u>d<u>!</u>!
  </code></p>
</blockquote>

<h2> Connecting Strictness to Streams </h2>

<p>As can be seen above, strictness and streams are tightly coupled. Here we present a theoretical evaluation (<img src="http://netsuperbrain.com/blog/wp-content/cache/tex_42d31315f777ae7b500fab09e354a93e.png" align="absmiddle" class="tex" alt="\leadsto" />) of a function at a given point in time. Here we introduce a new symbol we&#8217;ll call partial, <img src="http://netsuperbrain.com/blog/wp-content/cache/tex_fa922fca2ddd267ad530807d9222c03b.png" align="absmiddle" class="tex" alt="\partial" />, that represents a value that we have <em>no</em> information about at the given moment. <img src="http://netsuperbrain.com/blog/wp-content/cache/tex_2a95aaaf954c2187999c6357b04a58dd.png" align="absmiddle" class="tex" alt="\hat{x}" /> represents a symbol where everything is known and all other variables could mean either. So, for our <code>withNext'</code> function above, we may write the following equations:</p>

<p><center><img src="http://netsuperbrain.com/blog/wp-content/cache/tex_9915366037db2f1583b75d25d42f11f7.png" align="absmiddle" class="tex" alt="\mbox{\bf withNext' } \partial \leadsto \partial" /></center>
<center><img src="http://netsuperbrain.com/blog/wp-content/cache/tex_c548bb207e0f0c6b530fef3b02d2dddc.png" align="absmiddle" class="tex" alt="\mbox{\bf withNext' } (x:\partial) \leadsto (x,\partial):\partial" /></center></p>

<p>Note that our <img src="http://netsuperbrain.com/blog/wp-content/cache/tex_42d31315f777ae7b500fab09e354a93e.png" align="absmiddle" class="tex" alt="\leadsto" /> equations are the same as our strictness equations. Thus we may use these functions to prove invariants on our stream-based code.</p>

<h2> Example from Reactive </h2>

<p>Take the following <code>mappend</code> code from reactive:</p>


<div class="wp_syntax"><div class="code"><pre class="haskell haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">instance</span> <span style="color: #cccc00; font-weight: bold;">Ord</span> t <span style="color: #339933; font-weight: bold;">=&gt;</span> Monoid <span style="color: green;">&#40;</span>FutureG t a<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <span style="color: #5d478b; font-style: italic;">-- ...</span>
  <span style="color: #5d478b; font-style: italic;">-- Pick the earlier future.</span>
  Future <span style="color: green;">&#40;</span>s<span style="color: #339933; font-weight: bold;">,</span>a<span style="color: green;">&#41;</span> `mappend` Future <span style="color: green;">&#40;</span>t<span style="color: #339933; font-weight: bold;">,</span>b<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span>
    Future <span style="color: green;">&#40;</span>s `<span style="font-weight: bold;">min</span>` t<span style="color: #339933; font-weight: bold;">,</span> <span style="color: #06c; font-weight: bold;">if</span> s <span style="color: #339933; font-weight: bold;">&lt;=</span> t <span style="color: #06c; font-weight: bold;">then</span> a <span style="color: #06c; font-weight: bold;">else</span> b<span style="color: green;">&#41;</span></pre></div></div>


<p>Using strictness analysis, we can come up with the following <img src="http://netsuperbrain.com/blog/wp-content/cache/tex_42d31315f777ae7b500fab09e354a93e.png" align="absmiddle" class="tex" alt="\leadsto" /> equations.</p>

<p><center><img src="http://netsuperbrain.com/blog/wp-content/cache/tex_014cd0d9397234d0f0de4d8cd12986c0.png" align="absmiddle" class="tex" alt="\mbox{\bf mappend } (\mbox{\bf Future } \partial) (\mbox{\bf Future } x) \leadsto \partial" /></center>
<center><img src="http://netsuperbrain.com/blog/wp-content/cache/tex_12d74a73555e1ec60e42c0843aea2ac9.png" align="absmiddle" class="tex" alt="\mbox{\bf mappend } (\mbox{\bf Future }x) (\mbox{\bf Future }\partial) \leadsto \partial" /></center></p>

<p>This tells us that if we do not know anything about the tuples in the Future arguments to <em>mappend</em>, then we cannot know anything about the result. So a developer might want to maintain an invariant that <img src="http://netsuperbrain.com/blog/wp-content/cache/tex_7364debb5c15a45e2451b776e039543c.png" align="absmiddle" class="tex" alt="\mbox{\bf Future } x" /> implies that <img src="http://netsuperbrain.com/blog/wp-content/cache/tex_e66c706399f4c5452b8db550bf3f931f.png" align="absmiddle" class="tex" alt="x\leadsto (y,z)" />.</p>

<p>Continuing on&#8230;
<center><img src="http://netsuperbrain.com/blog/wp-content/cache/tex_0cbb403afe131a2fb19f0516e4c67b9f.png" align="absmiddle" class="tex" alt="\mbox{\bf mappend } (\mbox{\bf Future } (\partial, \partial)) (\mbox{\bf Future } (\hat{x},\hat{y})) \leadsto" /></center>
<center><img src="http://netsuperbrain.com/blog/wp-content/cache/tex_80fb27f56400f4b16b8d89ccdc6ac861.png" align="absmiddle" class="tex" alt="\mbox{\bf Future }(\mbox{\bf min }\partial\;\hat{x}, \mbox{\bf if } \partial <= \hat{x}\; \mbox{\bf then } \partial \;\mbox{\bf else } \hat{y} )" /></center></p>

<p>If we add some more invariants, we can go even further. Lets say that if we have the invariant that <img src="http://netsuperbrain.com/blog/wp-content/cache/tex_d1c1d9efa928a56adc22bdfb4dd137d1.png" align="absmiddle" class="tex" alt="\mbox{\bf Future t}" /> implies that <code>min (<img src="http://netsuperbrain.com/blog/wp-content/cache/tex_fa922fca2ddd267ad530807d9222c03b.png" align="absmiddle" class="tex" alt="\partial" /> :: t) (x :: t) <img src="http://netsuperbrain.com/blog/wp-content/cache/tex_42d31315f777ae7b500fab09e354a93e.png" align="absmiddle" class="tex" alt="\leadsto" /> x</code> and <code>(&lt;=) (<img src="http://netsuperbrain.com/blog/wp-content/cache/tex_fa922fca2ddd267ad530807d9222c03b.png" align="absmiddle" class="tex" alt="\partial" /> :: t) (x :: t) <img src="http://netsuperbrain.com/blog/wp-content/cache/tex_42d31315f777ae7b500fab09e354a93e.png" align="absmiddle" class="tex" alt="\leadsto" /> False</code>. Then we get a Future that allows us to <code>mappend</code> now with a past future and a future future.</p>

<p><center><img src="http://netsuperbrain.com/blog/wp-content/cache/tex_b3bae7b924926e0994022f14cda4282b.png" align="absmiddle" class="tex" alt="\mbox{\bf mappend } (\mbox{\bf Future } (\partial, \partial)) (\mbox{\bf Future } (\hat{x},\hat{y})) \leadsto\mbox{\bf Future }(\hat{x}, \hat{y} )" /></center></p>

<p>Verifying the the code is sufficiently lazy is now just a matter of seeing that these invariants are met.</p>
]]></content:encoded>
			<wfw:commentRss>http://netsuperbrain.com/blog/posts/analysis-of-lazy-stream-programs/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
