<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>The Comonad.Reader &#187; Algorithms</title>
	<atom:link href="http://comonad.com/reader/category/algorithms/feed/" rel="self" type="application/rss+xml" />
	<link>http://comonad.com/reader</link>
	<description>types, (co)monads, substructural logic</description>
	<lastBuildDate>Mon, 24 Oct 2022 17:48:27 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Fast Circular Substitution</title>
		<link>http://comonad.com/reader/2014/fast-circular-substitution/</link>
		<comments>http://comonad.com/reader/2014/fast-circular-substitution/#comments</comments>
		<pubDate>Tue, 30 Dec 2014 19:47:45 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Type Theory]]></category>
		<category><![CDATA[circular substitution]]></category>
		<category><![CDATA[functional programming]]></category>
		<category><![CDATA[HOAS]]></category>
		<category><![CDATA[syntax trees]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=956</guid>
		<description><![CDATA[Emil Axelsson and Koen Claessen wrote a functional pearl last year about Using Circular Programs for Higher-Order Syntax.
About 6 months ago I had an opportunity to play with this approach in earnest, and realized we can speed it up a great deal. This has kept coming up in conversation ever since, so I've decided to [...]]]></description>
			<content:encoded><![CDATA[<p>Emil Axelsson and Koen Claessen wrote a functional pearl last year about <a href="http://www.cse.chalmers.se/~emax/documents/axelsson2013using.pdf">Using Circular Programs for Higher-Order Syntax</a>.</p>
<p>About 6 months ago I had an opportunity to play with this approach in earnest, and realized we can speed it up a great deal. This has kept coming up in conversation ever since, so I've decided to write up an article here.</p>
<p>In my <a href="http://hackage.haskell.org/package/bound">bound</a> library I exploit the fact that monads are about substitution to make a monad transformer that manages substitution for me.</p>
<p>Here I'm going to take a more coupled approach.</p>
<p>To have a type system with enough complexity to be worth examining, I'll adapt Dan Doel's <a href="http://hub.darcs.net/dolio/upts">UPTS</a>, which is a pure type system with universe polymorphism. I won't finish the implementation here, but from where we get it should be obvious how to finish the job.</p>
<p><span id="more-956"></span></p>
<p>Unlike Axelsson and Claessen I'm not going to bother to abstract over my name representation.</p>
<p>To avoid losing the original name from the source, we'll just track names as strings with an integer counting the number of times it has been 'primed'. The name is purely for expository purposes, the real variable identifier is the number. We'll follow the Axelsson and Claessen convention of having the identifier assigned to each binder be larger than any one bound inside of it. If you don't need he original source names you can cull them from the representation, but they can be useful if you are representing a syntax tree for something you parsed and/or that you plan to pretty print later.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Name = Name <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="background-color: #efefbf; font-weight: bold;">String</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="background-color: #efefbf; font-weight: bold;">Int</span></a>
   <span style="color: #06c; font-weight: bold;">deriving</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Show"><span style="background-color: #efefbf; font-weight: bold;">Show</span></a>,<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Read"><span style="background-color: #efefbf; font-weight: bold;">Read</span></a><span style="color: green;">&#41;</span>
&nbsp;
hint :: Name -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="background-color: #efefbf; font-weight: bold;">String</span></a>
hint <span style="color: green;">&#40;</span>Name n _<span style="color: green;">&#41;</span> = n
&nbsp;
nameId :: Name -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="background-color: #efefbf; font-weight: bold;">Int</span></a>
nameId <span style="color: green;">&#40;</span>Name _ i<span style="color: green;">&#41;</span> = i
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Eq"><span style="background-color: #efefbf; font-weight: bold;">Eq</span></a> Name <span style="color: #06c; font-weight: bold;">where</span>
  <span style="color: green;">&#40;</span>==<span style="color: green;">&#41;</span> = <span style="color: green;">&#40;</span>==<span style="color: green;">&#41;</span> `on` nameId
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="background-color: #efefbf; font-weight: bold;">Ord</span></a> Name <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:compare"><span style="font-weight: bold;">compare</span></a> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:compare"><span style="font-weight: bold;">compare</span></a> `on` nameId
&nbsp;
prime :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="background-color: #efefbf; font-weight: bold;">String</span></a> -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="background-color: #efefbf; font-weight: bold;">Int</span></a> -&gt; Name
prime n i = Name n <span style="color: green;">&#40;</span>i + <span style="color: red;">1</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>So what is the language I want to work with?</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Level = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="background-color: #efefbf; font-weight: bold;">Int</span></a>
&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Constant
  = Level
  | LevelLiteral <span style="color: #5d478b; font-style: italic;">{-# UNPACK #-}</span> !Level
  | Omega
  <span style="color: #06c; font-weight: bold;">deriving</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Eq"><span style="background-color: #efefbf; font-weight: bold;">Eq</span></a>,<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="background-color: #efefbf; font-weight: bold;">Ord</span></a>,<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Show"><span style="background-color: #efefbf; font-weight: bold;">Show</span></a>,<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Read"><span style="background-color: #efefbf; font-weight: bold;">Read</span></a>,Typeable<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Term a
  = Free a
  | Bound <span style="color: #5d478b; font-style: italic;">{-# UNPACK #-}</span> !Name
  | Constant !Constant
  | Term a :+ <span style="color: #5d478b; font-style: italic;">{-# UNPACK #-}</span> !Level
  | Max  <span style="color: green;">&#91;</span>Term a<span style="color: green;">&#93;</span>
  | Type !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span>
  | Lam   <span style="color: #5d478b; font-style: italic;">{-# UNPACK #-}</span> !Name !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span> !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span>
  | Pi    <span style="color: #5d478b; font-style: italic;">{-# UNPACK #-}</span> !Name !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span> !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span>
  | Sigma <span style="color: #5d478b; font-style: italic;">{-# UNPACK #-}</span> !Name !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span> !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span>
  | App !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span> !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span>
  | Fst !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span>
  | Snd !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span>
  | Pair !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span> !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span> !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span>
  <span style="color: #06c; font-weight: bold;">deriving</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Show"><span style="background-color: #efefbf; font-weight: bold;">Show</span></a>,<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Read"><span style="background-color: #efefbf; font-weight: bold;">Read</span></a>,<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Eq"><span style="background-color: #efefbf; font-weight: bold;">Eq</span></a>,<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="background-color: #efefbf; font-weight: bold;">Ord</span></a>,<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a>,Foldable,Traversable,Typeable<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>That is perhaps a bit paranoid about remaining strict, but it seemed like a good idea at the time.</p>
<p>We can define capture avoiding substitution on terms:</p>
<pre class="haskell">&nbsp;
subst :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Eq"><span style="background-color: #efefbf; font-weight: bold;">Eq</span></a> a =&gt; a -&gt; Term a -&gt; Term a -&gt; Term a
subst a x y = y &gt;&gt;= \a' -&gt;
  <span style="color: #06c; font-weight: bold;">if</span> a == a'
    <span style="color: #06c; font-weight: bold;">then</span> x
    <span style="color: #06c; font-weight: bold;">else</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> a'
&nbsp;</pre>
<p>Now we finally need to implement Axelsson and Claessen's circular programming trick. Here we'll abstract over terms that allow us to find the highest bound value within them:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> Bindable t <span style="color: #06c; font-weight: bold;">where</span>
  bound :: t -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="background-color: #efefbf; font-weight: bold;">Int</span></a>
&nbsp;</pre>
<p>and instantiate it for our <code>Term</code> type</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Bindable <span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  bound Free<span style="color: green;">&#123;</span><span style="color: green;">&#125;</span>        = <span style="color: red;">0</span>
  bound Bound<span style="color: green;">&#123;</span><span style="color: green;">&#125;</span>       = <span style="color: red;">0</span> <span style="color: #5d478b; font-style: italic;">-- intentional!</span>
  bound Constant<span style="color: green;">&#123;</span><span style="color: green;">&#125;</span>    = <span style="color: red;">0</span>
  bound <span style="color: green;">&#40;</span>a :+ _<span style="color: green;">&#41;</span>      = bound a
  bound <span style="color: green;">&#40;</span>Max xs<span style="color: green;">&#41;</span>      = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:foldr"><span style="font-weight: bold;">foldr</span></a> <span style="color: green;">&#40;</span>\a r -&gt; bound a `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:max"><span style="font-weight: bold;">max</span></a>` r<span style="color: green;">&#41;</span> <span style="color: red;">0</span> xs
  bound <span style="color: green;">&#40;</span>Type t<span style="color: green;">&#41;</span>      = bound t
  bound <span style="color: green;">&#40;</span>Lam b t _<span style="color: green;">&#41;</span>   = nameId b `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:max"><span style="font-weight: bold;">max</span></a>` bound t
  bound <span style="color: green;">&#40;</span>Pi b t _<span style="color: green;">&#41;</span>    = nameId b `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:max"><span style="font-weight: bold;">max</span></a>` bound t
  bound <span style="color: green;">&#40;</span>Sigma b t _<span style="color: green;">&#41;</span> = nameId b `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:max"><span style="font-weight: bold;">max</span></a>` bound t
  bound <span style="color: green;">&#40;</span>App x y<span style="color: green;">&#41;</span>     = bound x `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:max"><span style="font-weight: bold;">max</span></a>`  bound y
  bound <span style="color: green;">&#40;</span>Fst t<span style="color: green;">&#41;</span>       = bound t
  bound <span style="color: green;">&#40;</span>Snd t<span style="color: green;">&#41;</span>       = bound t
  bound <span style="color: green;">&#40;</span>Pair t x y<span style="color: green;">&#41;</span>  = bound t `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:max"><span style="font-weight: bold;">max</span></a>` bound x `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:max"><span style="font-weight: bold;">max</span></a>` bound y
&nbsp;</pre>
<p>As in the original pearl we avoid traversing into the body of the binders, hence the _'s in the code above.</p>
<p>Now we can abstract over the pattern used to create a binder in the functional pearl, since we have multiple binder types in this syntax tree, and the code would get repetitive.</p>
<pre class="haskell">&nbsp;
binder :: Bindable t =&gt;
  <span style="color: green;">&#40;</span>Name -&gt; t<span style="color: green;">&#41;</span> -&gt;
  <span style="color: green;">&#40;</span>Name -&gt; t -&gt; r<span style="color: green;">&#41;</span> -&gt;
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="background-color: #efefbf; font-weight: bold;">String</span></a> -&gt; <span style="color: green;">&#40;</span>t -&gt; t<span style="color: green;">&#41;</span> -&gt; r
binder bd c n e = c b body <span style="color: #06c; font-weight: bold;">where</span>
  body = e <span style="color: green;">&#40;</span>bd b<span style="color: green;">&#41;</span>
  b = prime n <span style="color: green;">&#40;</span>bound body<span style="color: green;">&#41;</span>
&nbsp;
lam, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:pi"><span style="font-weight: bold;">pi</span></a>, sigma :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="background-color: #efefbf; font-weight: bold;">String</span></a> -&gt; Term a -&gt; <span style="color: green;">&#40;</span>Term a -&gt; Term a<span style="color: green;">&#41;</span> -&gt; Term a
lam s t   = binder Bound <span style="color: green;">&#40;</span>`Lam` t<span style="color: green;">&#41;</span> s
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:pi"><span style="font-weight: bold;">pi</span></a> s t    = binder Bound <span style="color: green;">&#40;</span>`Pi` t<span style="color: green;">&#41;</span> s
sigma s t = binder Bound <span style="color: green;">&#40;</span>`Sigma` t<span style="color: green;">&#41;</span> s
&nbsp;</pre>
<p>We may not always want to give names to the variables we capture, so let's define:</p>
<pre>
lam_, pi_, sigma_ :: Term a -> (Term a -> Term a) -> Term a
lam_   = lam "_"
pi_    = pi "_"
sigma_ = sigma "_"
</pre>
<p>Now, here's the interesting part. The problem with Axelsson and Claessen's original trick is that every substitution is being handled separately. This means that if you were to write a monad for doing substitution with it, it'd actually be quite slow. You have to walk the syntax tree over and over and over.</p>
<p>We can fuse these together by making a single pass:</p>
<pre class="haskell">&nbsp;
instantiate :: Name -&gt; t -&gt; IntMap t -&gt; IntMap t
instantiate = IntMap.insert . nameId
&nbsp;
rebind :: IntMap <span style="color: green;">&#40;</span>Term b<span style="color: green;">&#41;</span> -&gt; Term a -&gt; <span style="color: green;">&#40;</span>a -&gt; Term b<span style="color: green;">&#41;</span> -&gt; Term b
rebind env xs0 f = go xs0 <span style="color: #06c; font-weight: bold;">where</span>
  go = \<span style="color: #06c; font-weight: bold;">case</span>
    Free a       -&gt; f a
    Bound b      -&gt; env IntMap.! nameId b
    Constant c   -&gt; Constant c
    m :+ n       -&gt; go m :+ n
    Type t       -&gt; Type <span style="color: green;">&#40;</span>go t<span style="color: green;">&#41;</span>
    Max xs       -&gt; Max <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> go xs<span style="color: green;">&#41;</span>
    Lam b t e    -&gt; lam   <span style="color: green;">&#40;</span>hint b<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>go t<span style="color: green;">&#41;</span> $ \v -&gt;
      rebind <span style="color: green;">&#40;</span>instantiate b v env<span style="color: green;">&#41;</span> e f
    Pi b t e     -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:pi"><span style="font-weight: bold;">pi</span></a>    <span style="color: green;">&#40;</span>hint b<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>go t<span style="color: green;">&#41;</span> $ \v -&gt;
      rebind <span style="color: green;">&#40;</span>instantiate b v env<span style="color: green;">&#41;</span> e f
    Sigma b t e  -&gt; sigma <span style="color: green;">&#40;</span>hint b<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>go t<span style="color: green;">&#41;</span> $ \v -&gt;
      rebind <span style="color: green;">&#40;</span>instantiate b v env<span style="color: green;">&#41;</span> e f
    App x y      -&gt; App <span style="color: green;">&#40;</span>go x<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>go y<span style="color: green;">&#41;</span>
    Fst x        -&gt; Fst <span style="color: green;">&#40;</span>go x<span style="color: green;">&#41;</span>
    Snd x        -&gt; Snd <span style="color: green;">&#40;</span>go x<span style="color: green;">&#41;</span>
    Pair t x y   -&gt; Pair <span style="color: green;">&#40;</span>go t<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>go x<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>go y<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Note that the <code>Lam</code>, <code>Pi</code> and <code>Sigma</code> cases just extend the current environment.</p>
<p>With that now we can upgrade the pearl's encoding to allow for an actual Monad in the same sense as <code>bound</code>.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Applicative Term <span style="color: #06c; font-weight: bold;">where</span>
  pure = Free
  <span style="color: green;">&#40;</span>&lt; *&gt;<span style="color: green;">&#41;</span> = ap
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> Term <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> = Free
  <span style="color: green;">&#40;</span>&gt;&gt;=<span style="color: green;">&#41;</span> = rebind IntMap.empty
&nbsp;</pre>
<p>To show that we can work with this syntax tree representation, let's write an evaluator from it to weak head normal form:</p>
<p>First we'll need some helpers:</p>
<pre class="haskell">&nbsp;
apply :: Term a -&gt; <span style="color: green;">&#91;</span>Term a<span style="color: green;">&#93;</span> -&gt; Term a
apply = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:foldl"><span style="font-weight: bold;">foldl</span></a> App
&nbsp;
rwhnf :: IntMap <span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span> -&gt;
  <span style="color: green;">&#91;</span>Term a<span style="color: green;">&#93;</span> -&gt; Term a -&gt; Term a
rwhnf env stk     <span style="color: green;">&#40;</span>App f x<span style="color: green;">&#41;</span>
  = rwhnf env <span style="color: green;">&#40;</span>rebind env x Free:stk<span style="color: green;">&#41;</span> f
rwhnf env <span style="color: green;">&#40;</span>x:stk<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>Lam b _ e<span style="color: green;">&#41;</span>
  = rwhnf <span style="color: green;">&#40;</span>instantiate b x env<span style="color: green;">&#41;</span> stk e
rwhnf env stk <span style="color: green;">&#40;</span>Fst e<span style="color: green;">&#41;</span>
  = <span style="color: #06c; font-weight: bold;">case</span> rwhnf env <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span> e <span style="color: #06c; font-weight: bold;">of</span>
  Pair _ e' _ -&gt; rwhnf env stk e'
  e'          -&gt; Fst e'
rwhnf env stk <span style="color: green;">&#40;</span>Snd e<span style="color: green;">&#41;</span>
  = <span style="color: #06c; font-weight: bold;">case</span> rwhnf env <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span> e <span style="color: #06c; font-weight: bold;">of</span>
  Pair _ _ e' -&gt; rwhnf env stk e'
  e'          -&gt; Snd e'
rwhnf env stk e
  = apply <span style="color: green;">&#40;</span>rebind env e Free<span style="color: green;">&#41;</span> stk
&nbsp;</pre>
<p>Then we can start off the <code>whnf</code> by calling our helper with an initial starting environment:</p>
<pre class="haskell">&nbsp;
whnf :: Term a -&gt; Term a
whnf = rwhnf IntMap.empty <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span>
&nbsp;</pre>
<p>So what have we given up? Well, <code>bound</code> automatically lets you compare terms for alpha equivalence by quotienting out the placement of "F" terms in the syntax tree. Here we have a problem in that the identifiers we get assigned aren't necessarily canonical.</p>
<p>But we can get the same identifiers out by just using the monad above:</p>
<pre class="haskell">&nbsp;
alphaEq :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Eq"><span style="background-color: #efefbf; font-weight: bold;">Eq</span></a> a =&gt; Term a -&gt; Term a -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a>
alphaEq = <span style="color: green;">&#40;</span>==<span style="color: green;">&#41;</span> `on` liftM <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a>
&nbsp;</pre>
<p>It makes me a bit uncomfortable that our monad is only up to alpha equivalence and that <code>liftM</code> swaps out the identifiers used throughout the entire syntax tree, and we've also lost the ironclad protection against exotic terms.</p>
<p>But overall, this is a much faster version of Axelsson and Claessen's trick and it can be used as a drop-in replacement for something like <code>bound</code> in many cases, and unlike bound, it lets you use HOAS-style syntax for constructing <code>lam</code>, <code>pi</code> and <code>sigma</code> terms.</p>
<p>With pattern synonyms you can prevent the user from doing bad things as well. Once 7.10 ships you'd be able to use a bidirectional pattern synonym for <code>Pi</code>, <code>Sigma</code> and <code>Lam</code> to hide the real constructors behind. I'm not yet sure of the "best practices" in this area.</p>
<p>Here's the code all in one place:</p>
<p>[<a href='http://comonad.com/reader/wp-content/uploads/2014/12/Circular.hs'>Download Circular.hs</a>]</p>
<p>Happy Holidays,<br />
-Edward</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2014/fast-circular-substitution/feed/</wfw:commentRss>
		<slash:comments>48</slash:comments>
		</item>
		<item>
		<title>Mirrored Lenses</title>
		<link>http://comonad.com/reader/2012/mirrored-lenses/</link>
		<comments>http://comonad.com/reader/2012/mirrored-lenses/#comments</comments>
		<pubDate>Mon, 25 Jun 2012 03:38:41 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Lenses]]></category>
		<category><![CDATA[accessors]]></category>
		<category><![CDATA[functional references]]></category>
		<category><![CDATA[lens families]]></category>
		<category><![CDATA[van Laarhoven]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=600</guid>
		<description><![CDATA[Lenses are a great way to deal with functional references, but there are two common issues that arise from their use. 

There is a long-standing folklore position that lenses do not support polymorphic updates. This has actually caused a fair bit of embarrassment for the folks who'd like to incorporate lenses in any Haskell record [...]]]></description>
			<content:encoded><![CDATA[<p>Lenses are a great way to deal with functional references, but there are two common issues that arise from their use. </p>
<ol>
<li>There is a long-standing folklore position that lenses do not support polymorphic updates. This has actually caused a fair bit of embarrassment for the folks who'd like to incorporate lenses in any Haskell record system improvement.</li>
<li>Access control. It'd be nice to have read-only or write-only properties -- "one-way" or "mirrored" lenses, as it were. Moreover, lenses are commonly viewed as an all or nothing proposition, in that it is hard to mix them with arbitrary user functions.</li>
<li>Finally there is a bit of a cult around trying to generalize lenses by smashing a monad in the middle of them somewhere, it would be nice to be able to get into a list and work with each individual element in it without worrying about someone mucking up our lens laws, and perhaps avoid the whole generalized lens issue entirely.</li>
</ol>
<p>We'll take a whack at each of these concerns in turn today.<br />
<span id="more-600"></span></p>
<pre lang='haskell'>
   {-# LANGUAGE Rank2Types #-}  -- we'll relax this later
   import Data.Complex -- for complex examples
</pre>
<p>First, let us consider the type of van Laarhoven lenses:</p>
<pre lang='haskell'>
type Lens a b =
  forall f. Functor f =>
  (b -> f b) -> a -> f a
</pre>
<p>with a couple of examples:</p>
<pre class="haskell">&nbsp;
realLens :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:RealFloat"><span style="background-color: #efefbf; font-weight: bold;">RealFloat</span></a> a =&gt; Lens <span style="color: green;">&#40;</span>Complex a<span style="color: green;">&#41;</span> a
realLens f <span style="color: green;">&#40;</span>r :+ i<span style="color: green;">&#41;</span> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>:+ i<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>f r<span style="color: green;">&#41;</span>
&nbsp;
imagLens :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:RealFloat"><span style="background-color: #efefbf; font-weight: bold;">RealFloat</span></a> a =&gt; Lens <span style="color: green;">&#40;</span>Complex a<span style="color: green;">&#41;</span> a
imagLens f <span style="color: green;">&#40;</span>r :+ i<span style="color: green;">&#41;</span> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>r :+<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>f i<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>These lenses have some very nice properties that we're going to exploit. By far their nicest property is that you can compose them using just <code>(.)</code> and <code>id</code> from the <code>Prelude</code> rather than having to go off and write a <code>Category</code>.</p>
<h2>Lens Families</h2>
<p><a href="http://r6.ca/blog/20120623T104901Z.html">Russell O'Connor recently noted that these lenses permit polymorphic update</a> if you simply generalize their type signature to</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> LensFamily a b c d =
  <span style="color: #06c; font-weight: bold;">forall</span> f. <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt;
  <span style="color: green;">&#40;</span>c -&gt; f d<span style="color: green;">&#41;</span> -&gt; a -&gt; f b
&nbsp;</pre>
<p>I'd like to note that you can't just let these 4 arguments vary with complete impunity, so I'll be referring to these as "lens families" rather than polymorphic lenses, a point that I'll address further below. In short, we want the original lens laws to still hold in spite of the generalized type signature, and this forces some of these types to be related. </p>
<p>As an aside, each of the other lens types admit this same generalization! For instance the <code>Lens</code> type in <a href="http://hackage.haskell.org/package/data-lens">data-lens</a> can be generalized using an indexed store comonad:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Store c d b = Store <span style="color: green;">&#40;</span>d -&gt; b<span style="color: green;">&#41;</span> c
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>Store c d<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>Store g c<span style="color: green;">&#41;</span> = Store <span style="color: green;">&#40;</span>f . g<span style="color: green;">&#41;</span> c
&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> DataLensFamily a b c d = DataLensFamily <span style="color: green;">&#40;</span>a -&gt; Store c d b<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>and we can freely convert back and forth to van Laarhoven lens families:</p>
<pre class="haskell">&nbsp;
dlens :: LensFamily a b c d -&gt; DataLensFamily a b c d
dlens l = DataLensFamily <span style="color: green;">&#40;</span>l <span style="color: green;">&#40;</span>Store <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
plens :: DataLensFamily a b c d -&gt; LensFamily a b c d
plens <span style="color: green;">&#40;</span>DataLensFamily l<span style="color: green;">&#41;</span> f a = <span style="color: #06c; font-weight: bold;">case</span> l a <span style="color: #06c; font-weight: bold;">of</span>
  Store g c -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> g <span style="color: green;">&#40;</span>f c<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>I leave it as an exercise to the reader to generalize the other lens types, but we'll stick to van Laarhoven lens families almost exclusively below.</p>
<p>As Russell noted, we can define functions to get, modify and set the target of a lens very easily. I'll create local names for <code>Identity</code> and <code>Const</code>, mostly to help give nicer error messages later.</p>
<p>We can read from a lens family:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">infixl</span> <span style="color: red;">8</span> ^.
<span style="color: #06c; font-weight: bold;">newtype</span> Getting b a = Getting <span style="color: green;">&#123;</span> got :: b <span style="color: green;">&#125;</span>
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>Getting b<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> _ <span style="color: green;">&#40;</span>Getting b<span style="color: green;">&#41;</span> = Getting b
<span style="color: green;">&#40;</span>^.<span style="color: green;">&#41;</span> :: a -&gt; <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>c -&gt; Getting c d<span style="color: green;">&#41;</span> -&gt; a -&gt; Getting c b<span style="color: green;">&#41;</span> -&gt; c
x ^. l = got <span style="color: green;">&#40;</span>l Getting x<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>We can modify the target of the lens:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Setting a = Setting <span style="color: green;">&#123;</span> unsetting :: a <span style="color: green;">&#125;</span>
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> Setting <span style="color: #06c; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>Setting a<span style="color: green;">&#41;</span> = Setting <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">infixr</span> <span style="color: red;">4</span> %=
<span style="color: green;">&#40;</span>%=<span style="color: green;">&#41;</span> :: <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>c -&gt; Setting d<span style="color: green;">&#41;</span> -&gt; a -&gt; Setting b<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>c -&gt; d<span style="color: green;">&#41;</span> -&gt; a -&gt; b
l %= f = unsetting . l <span style="color: green;">&#40;</span>Setting . f<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>We can set the target of the lens with impunity:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">infixr</span> <span style="color: red;">4</span> ^=
<span style="color: green;">&#40;</span>^=<span style="color: green;">&#41;</span> :: <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>c -&gt; Setting d<span style="color: green;">&#41;</span> -&gt; a -&gt; Setting b<span style="color: green;">&#41;</span> -&gt; d -&gt; a -&gt; b
l ^= v = l %= <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a> v
&nbsp;</pre>
<p>We can build a lens family from a getter/setter pair</p>
<pre class="haskell">&nbsp;
lens :: <span style="color: green;">&#40;</span>a -&gt; c<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>a -&gt; d -&gt; b<span style="color: green;">&#41;</span> -&gt; LensFamily a b c d
lens f g h a = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>g a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>h <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>or from a family of isomorphisms:</p>
<pre class="haskell">&nbsp;
iso :: <span style="color: green;">&#40;</span>a -&gt; c<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>d -&gt; b<span style="color: green;">&#41;</span> -&gt; LensFamily a b c d
iso f g h a = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> g <span style="color: green;">&#40;</span>h <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>With these combinators in hand, we need some actual lens families to play with. Fortunately they are just as easy to construct as simple lenses. The only thing that changes is the type signature.  </p>
<pre class="haskell">&nbsp;
fstLens :: LensFamily <span style="color: green;">&#40;</span>a,c<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>b,c<span style="color: green;">&#41;</span> a b
fstLens f <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>\x -&gt; <span style="color: green;">&#40;</span>x,b<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span>
&nbsp;
sndLens :: LensFamily <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>a,c<span style="color: green;">&#41;</span> b c
sndLens f <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>,<span style="color: green;">&#41;</span> a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>f b<span style="color: green;">&#41;</span>
&nbsp;
swap :: <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>b,a<span style="color: green;">&#41;</span>
swap <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> = <span style="color: green;">&#40;</span>b,a<span style="color: green;">&#41;</span>
&nbsp;
swapped :: LensFamily <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>c,d<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>b,a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>d,c<span style="color: green;">&#41;</span>
swapped = iso swap swap
&nbsp;</pre>
<p>These can also build 'traditional' lenses:</p>
<pre class="haskell">&nbsp;
negated :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="background-color: #efefbf; font-weight: bold;">Num</span></a> a =&gt; Lens a a
negated = iso <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:negate"><span style="font-weight: bold;">negate</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:negate"><span style="font-weight: bold;">negate</span></a>
&nbsp;</pre>
<p>And since <code>Lens</code> and <code>LensFamily</code> are both type aliases, we can freely mix and match lenses with lens families:</p>
<pre class="haskell">&nbsp;
ghci&gt; <span style="color: green;">&#40;</span><span style="color: red;">1</span>:<span style="color: red;">+2</span>,<span style="color: red;">3</span><span style="color: green;">&#41;</span> ^.fstLens.realLens
<span style="color: red;">1.0</span>
ghci&gt; fstLens . realLens ^= <span style="color: red;">4</span> $ <span style="color: green;">&#40;</span><span style="color: red;">1</span>:<span style="color: red;">+2</span>,<span style="color: red;">3</span><span style="color: green;">&#41;</span>
<span style="color: green;">&#40;</span><span style="color: red;">4.0</span> :+ <span style="color: red;">2.0</span>,<span style="color: red;">3</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>But, we can now change types with our lens updates!</p>
<pre class="haskell">&nbsp;
ghci&gt; <span style="color: green;">&#40;</span>fstLens . sndLens ^= <span style="color: #3c7331;">&quot;hello&quot;</span><span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span><span style="color: red;">1</span>,<span style="color: green;">&#40;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>,<span style="color: red;">3</span><span style="color: green;">&#41;</span>
<span style="color: green;">&#40;</span><span style="color: green;">&#40;</span><span style="color: red;">1</span>,<span style="color: #3c7331;">&quot;hello&quot;</span><span style="color: green;">&#41;</span>,<span style="color: red;">3</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>We can even do things like use the combinator</p>
<pre class="haskell">&nbsp;
traverseLens :: <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>c -&gt; c<span style="color: green;">&#41;</span> -&gt; a -&gt; b<span style="color: green;">&#41;</span> -&gt; a -&gt; b
traverseLens f = f <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a>
&nbsp;</pre>
<p>to project a <code>Functor</code> out through an appropriate lens family:</p>
<pre class="haskell">&nbsp;
ghci&gt; :t traverseLens <span style="color: green;">&#40;</span>fstLens . sndLens<span style="color: green;">&#41;</span>
traverseLens <span style="color: green;">&#40;</span>fstLens . sndLens<span style="color: green;">&#41;</span>
  :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>a, f b<span style="color: green;">&#41;</span>, c<span style="color: green;">&#41;</span> -&gt; f <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>a, b<span style="color: green;">&#41;</span>, c<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>That takes care of polymorphic updates. </p>
<h2>Why is it a Lens Family?</h2>
<p>So, why do I use the term "lens family" rather than "polymorphic lens"?</p>
<p>In order for the lens laws to hold, the 4 types parameterizing our lens family must be interrelated.</p>
<p>In particular you need to be able to put back (with <code>^=</code>) what you get out of the lens (with <code>^.</code>) and put multiple times.</p>
<p>This effectively constrains the space of possible legal lens families to those where there exists an index kind <code>i</code>, and two type families <code>outer :: i -> *</code>, and <code>inner :: i -> *</code>. If this were a viable type signature, then each lens family would actually have 2 parameters, yielding something like:</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- pseudo-Haskell</span>
<span style="color: #5d478b; font-style: italic;">-- type LensFamily outer inner =</span>
<span style="color: #5d478b; font-style: italic;">--    forall a b. LensFamily (outer a) (outer b) (inner a) (inner b)</span>
&nbsp;</pre>
<p>but you can't pass in type families as arguments like that, and even if you could, their lack of injectivity doesn't give the type checker enough to work with to compose your lenses. By specifying all 4 type arguments independently, we give the compiler enough to work with. But since the arguments aren't just freely polymorphic and are instead related by these index types, I'm choosing to call them "lens families" rather than "polymorphic lenses".</p>
<h2>Getters</h2>
<p>Note, we didn't use the full polymorphism of the van Laarhoven lenses in the signatures of <code>(^.)</code>, <code>(%=)</code> and <code>(^=)</code> above.</p>
<p>What happens when we restrict the type of <code>Functor</code> we're allowed to pass to our lens?</p>
<p>If we generalize the type of our getter ever so slightly from the type we pass to <code>(^.)</code> to permit composition, we get:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Getter a c = <span style="color: #06c; font-weight: bold;">forall</span> r d b. <span style="color: green;">&#40;</span>c -&gt; Getting r d<span style="color: green;">&#41;</span> -&gt; a -&gt; Getting r b
&nbsp;</pre>
<p>and we can make getters out of arbitrary Haskell functions that we have lying around with</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- | build a getting out of a function</span>
getting :: <span style="color: green;">&#40;</span>a -&gt; b<span style="color: green;">&#41;</span> -&gt; Getter a b
getting g f = Getting . got . f . g
&nbsp;</pre>
<p>For example:</p>
<pre class="haskell">&nbsp;
getFst :: Getter <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> a
getFst = getting <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fst"><span style="font-weight: bold;">fst</span></a>
&nbsp;
getSnd :: Getter <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> b
getSnd = getting <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:snd"><span style="font-weight: bold;">snd</span></a>
&nbsp;</pre>
<p>But this is particularly nice for things that <em>can't</em> be made into real lenses or lens families, because of loss of information:</p>
<pre class="haskell">&nbsp;
getPhase :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:RealFloat"><span style="background-color: #efefbf; font-weight: bold;">RealFloat</span></a> a =&gt; Getter <span style="color: green;">&#40;</span>Complex a<span style="color: green;">&#41;</span> a
getPhase = getting phase
&nbsp;
getAbs, getSignum  :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="background-color: #efefbf; font-weight: bold;">Num</span></a> a =&gt; Getter a a
getAbs = getting <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:abs"><span style="font-weight: bold;">abs</span></a>
getSignum = getting <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:signum"><span style="font-weight: bold;">signum</span></a>
&nbsp;</pre>
<p>Notably, <code>getMagnitude</code> and <code>getPhase</code> can't be legal lenses because when the <code>magnitude</code> is 0, you lose <code>phase</code> information.</p>
<p>These can be mixed and matched with other lenses when dereferencing with <code>(^.)</code></p>
<pre class="haskell">&nbsp;
ghci&gt; <span style="color: green;">&#40;</span><span style="color: red;">0</span>,<span style="color: green;">&#40;</span><span style="color: red;">1</span>:<span style="color: red;">+2</span>,<span style="color: red;">3</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> ^. getting <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:snd"><span style="font-weight: bold;">snd</span></a> . fstLens . getting magnitude
<span style="color: red;">2.23606797749979</span>
&nbsp;</pre>
<p>But we get a type error when we attempt to write to a <code>Getter</code>.</p>
<pre class="haskell">&nbsp;
ghci&gt; getting magnitude ^= <span style="color: red;">12</span>
&lt;interactive&gt;:<span style="color: red;">2</span>:<span style="color: red;">1</span>:
    Couldn't match expected <span style="color: #06c; font-weight: bold;">type</span> `Setting d0'
                with actual <span style="color: #06c; font-weight: bold;">type</span> `Getting r0 d1'
    Expected <span style="color: #06c; font-weight: bold;">type</span>: <span style="color: green;">&#40;</span>c0 -&gt; Setting d0<span style="color: green;">&#41;</span> -&gt; a1 -&gt; Setting b1
      Actual <span style="color: #06c; font-weight: bold;">type</span>: <span style="color: green;">&#40;</span>c0 -&gt; Getting r0 d1<span style="color: green;">&#41;</span> -&gt; a0 -&gt; Getting r0 b0
    In the <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> <span style="color: #06c; font-weight: bold;">type</span> <span style="color: #06c; font-weight: bold;">of</span> a call <span style="color: #06c; font-weight: bold;">of</span> `getting'
    In the first argument <span style="color: #06c; font-weight: bold;">of</span> `<span style="color: green;">&#40;</span>^=<span style="color: green;">&#41;</span>', namely `getting magnitude'
&lt;/interactive&gt;</pre>
<h2>Setters</h2>
<p>So what about write-only properties?</p>
<p>These have a less satisfying solution. We have to break our lens family structure slightly to make something that can strictly <em>only</em> be written to, by disabling the ability to read our current value entirely. </p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Setter a d b = <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> -&gt; Setting d<span style="color: green;">&#41;</span> -&gt; a -&gt; Setting b
&nbsp;
setting :: <span style="color: green;">&#40;</span>a -&gt; d -&gt; b<span style="color: green;">&#41;</span> -&gt; Setter a d b
setting f g a = Setting <span style="color: green;">&#40;</span>f a <span style="color: green;">&#40;</span>unsetting <span style="color: green;">&#40;</span>g <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Now we can make setters out of functions that take two arguments:</p>
<pre class="haskell">&nbsp;
plus, times :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="background-color: #efefbf; font-weight: bold;">Num</span></a> a =&gt; Setter a a a
plus = setting <span style="color: green;">&#40;</span>+<span style="color: green;">&#41;</span>
times = setting <span style="color: green;">&#40;</span>*<span style="color: green;">&#41;</span>
&nbsp;</pre>
<pre class="haskell">&nbsp;
ghci&gt; setting <span style="color: green;">&#40;</span>+<span style="color: green;">&#41;</span> ^= <span style="color: red;">12</span> $ <span style="color: red;">32</span>
<span style="color: red;">44</span>
ghci&gt; fstLens . setting <span style="color: green;">&#40;</span>*<span style="color: green;">&#41;</span> ^= <span style="color: red;">12</span> $ <span style="color: green;">&#40;</span><span style="color: red;">2</span>,<span style="color: red;">3</span><span style="color: green;">&#41;</span>
<span style="color: green;">&#40;</span><span style="color: red;">24</span>,<span style="color: red;">3</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>However, these lenses have the unsatisfying property that they can only be placed last in the chain of lenses we're setting. </p>
<pre class="haskell">&nbsp;
ghci&gt; <span style="color: green;">&#40;</span>setting <span style="color: green;">&#40;</span>+<span style="color: green;">&#41;</span> . realLens ^= <span style="color: red;">12</span><span style="color: green;">&#41;</span> <span style="color: red;">1</span>
&lt;interactive&gt;:<span style="color: red;">15</span>:<span style="color: red;">16</span>:
    Couldn't match expected <span style="color: #06c; font-weight: bold;">type</span> `<span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>' with actual <span style="color: #06c; font-weight: bold;">type</span> `Complex d0'
    Expected <span style="color: #06c; font-weight: bold;">type</span>: <span style="color: green;">&#40;</span>d0 -&gt; Setting d0<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> -&gt; Setting b0
      Actual <span style="color: #06c; font-weight: bold;">type</span>: <span style="color: green;">&#40;</span>d0 -&gt; Setting d0<span style="color: green;">&#41;</span>
                   -&gt; Complex d0 -&gt; Setting <span style="color: green;">&#40;</span>Complex d0<span style="color: green;">&#41;</span>
    In the second argument <span style="color: #06c; font-weight: bold;">of</span> `<span style="color: green;">&#40;</span>.<span style="color: green;">&#41;</span>', namely `realLens'
    In the first argument <span style="color: #06c; font-weight: bold;">of</span> `<span style="color: green;">&#40;</span>^=<span style="color: green;">&#41;</span>', namely `setting <span style="color: green;">&#40;</span>+<span style="color: green;">&#41;</span> . realLens'
&lt;/interactive&gt;</pre>
<p>This isn't surprising, if you consider that to compose <code>data-lens</code> lenses you need to use <code>%=</code> to chain setters.</p>
<h2>Modifiers</h2>
<p>So what do we need to do to make a lens we can only modify but not read?</p>
<p>Lets restore the lens family structure!</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Modifier a b c d = <span style="color: green;">&#40;</span>c -&gt; Setting d<span style="color: green;">&#41;</span> -&gt; a -&gt; Setting b
&nbsp;
modifying :: <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>c -&gt; d<span style="color: green;">&#41;</span> -&gt; a -&gt; b<span style="color: green;">&#41;</span> -&gt; Modifier a b c d
modifying f g a = Setting <span style="color: green;">&#40;</span>f <span style="color: green;">&#40;</span>unsetting . g<span style="color: green;">&#41;</span> a<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p><code>modifying</code> makes a modify-only lens family you can modify using local information, but can't tell anyone about the contents of.</p>
<p>This lets us work with a lens over a variable number of elements in a structure, without worrying about a user accidentally "putting back" too many or too few entries.</p>
<pre class="haskell">&nbsp;
ghci&gt; modifying <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:map"><span style="font-weight: bold;">map</span></a> %= <span style="color: green;">&#40;</span><span style="color: red;">+1</span><span style="color: green;">&#41;</span> $ <span style="color: green;">&#91;</span><span style="color: red;">1</span>,<span style="color: red;">2</span>,<span style="color: red;">3</span><span style="color: green;">&#93;</span>
<span style="color: green;">&#91;</span><span style="color: red;">2</span>,<span style="color: red;">3</span>,<span style="color: red;">4</span><span style="color: green;">&#93;</span>
&nbsp;</pre>
<p>They can be composed with other lenses:</p>
<pre class="haskell">&nbsp;
ghci&gt; modifying <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:map"><span style="font-weight: bold;">map</span></a> . sndLens %= <span style="color: green;">&#40;</span><span style="color: red;">+1</span><span style="color: green;">&#41;</span> $ <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="color: #3c7331;">&quot;hello&quot;</span>,<span style="color: red;">1</span><span style="color: green;">&#41;</span>,<span style="color: green;">&#40;</span><span style="color: #3c7331;">&quot;goodbye&quot;</span>,<span style="color: red;">2</span><span style="color: green;">&#41;</span><span style="color: green;">&#93;</span>
<span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="color: #3c7331;">&quot;hello&quot;</span>,<span style="color: red;">2</span><span style="color: green;">&#41;</span>,<span style="color: green;">&#40;</span><span style="color: #3c7331;">&quot;goodbye&quot;</span>,<span style="color: red;">3</span><span style="color: green;">&#41;</span><span style="color: green;">&#93;</span>
&nbsp;</pre>
<p>and unlike with a <code>Setter</code>, you can compose a <code>Modifier</code> with a <code>Modifier</code>:</p>
<pre class="haskell">&nbsp;
modifying <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> . modifying <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a>
  :: <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> g, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f<span style="color: green;">&#41;</span> =&gt;
     <span style="color: green;">&#40;</span>c -&gt; Setting d<span style="color: green;">&#41;</span> -&gt; f <span style="color: green;">&#40;</span>g c<span style="color: green;">&#41;</span> -&gt; Setting <span style="color: green;">&#40;</span>f <span style="color: green;">&#40;</span>g d<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>but they cannot be read from directly:</p>
<pre class="haskell">&nbsp;
ghci&gt; <span style="color: green;">&#91;</span><span style="color: red;">1</span>,<span style="color: red;">2</span>,<span style="color: red;">3</span><span style="color: green;">&#93;</span> ^. modifying <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a>
&lt;interactive&gt;:<span style="color: red;">18</span>:<span style="color: red;">12</span>:
    Couldn't match expected <span style="color: #06c; font-weight: bold;">type</span> `Getting c0 d0'
                with actual <span style="color: #06c; font-weight: bold;">type</span> `Setting d1'
    Expected <span style="color: #06c; font-weight: bold;">type</span>: <span style="color: green;">&#40;</span>c0 -&gt; Getting c0 d0<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#91;</span>t0<span style="color: green;">&#93;</span> -&gt; Getting c0 b1
      Actual <span style="color: #06c; font-weight: bold;">type</span>: Modifier a0 b0 c0 d1
    In the <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> <span style="color: #06c; font-weight: bold;">type</span> <span style="color: #06c; font-weight: bold;">of</span> a call <span style="color: #06c; font-weight: bold;">of</span> `modifying'
    In the second argument <span style="color: #06c; font-weight: bold;">of</span> `<span style="color: green;">&#40;</span>^.<span style="color: green;">&#41;</span>', namely `modifying <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:map"><span style="font-weight: bold;">map</span></a>'
&lt;/interactive&gt;</pre>
<p>We can map over restricted domains:</p>
<pre class="haskell">&nbsp;
reals :: <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:RealFloat"><span style="background-color: #efefbf; font-weight: bold;">RealFloat</span></a> a, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:RealFloat"><span style="background-color: #efefbf; font-weight: bold;">RealFloat</span></a> b<span style="color: green;">&#41;</span> =&gt; Modifier <span style="color: green;">&#40;</span>Complex a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>Complex b<span style="color: green;">&#41;</span> a b
reals = modifying <span style="color: green;">&#40;</span>\f <span style="color: green;">&#40;</span>r :+ i<span style="color: green;">&#41;</span> -&gt; f r :+ f i<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>and everything still composes:</p>
<pre class="haskell">&nbsp;
ghci&gt; reals %= <span style="color: green;">&#40;</span><span style="color: red;">+1</span><span style="color: green;">&#41;</span> $  <span style="color: red;">1</span> :+ <span style="color: red;">2</span>
<span style="color: red;">2</span> :+ <span style="color: red;">3</span>
ghci&gt; fstLens . reals %= <span style="color: green;">&#40;</span><span style="color: red;">+1</span><span style="color: green;">&#41;</span> $ <span style="color: green;">&#40;</span><span style="color: red;">1</span> :+ <span style="color: red;">2</span>, <span style="color: red;">4</span><span style="color: green;">&#41;</span>
<span style="color: green;">&#40;</span><span style="color: red;">2.0</span> :+ <span style="color: red;">3.0</span>,<span style="color: red;">4</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>These aren't limited to actions that map over the entire structure, however!</p>
<pre class="haskell">&nbsp;
ghci&gt; :m + Data.Lens
ghci&gt; modifying <span style="color: green;">&#40;</span>`adjust` <span style="color: #3c7331;">&quot;goodbye&quot;</span><span style="color: green;">&#41;</span> %= <span style="color: green;">&#40;</span><span style="color: red;">+1</span><span style="color: green;">&#41;</span> $
      fromList <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="color: #3c7331;">&quot;hello&quot;</span>,<span style="color: red;">1</span><span style="color: green;">&#41;</span>,<span style="color: green;">&#40;</span><span style="color: #3c7331;">&quot;goodbye&quot;</span>,<span style="color: red;">2</span><span style="color: green;">&#41;</span><span style="color: green;">&#93;</span>
fromList <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="color: #3c7331;">&quot;goodbye&quot;</span>,<span style="color: red;">3</span><span style="color: green;">&#41;</span>,<span style="color: green;">&#40;</span><span style="color: #3c7331;">&quot;hello&quot;</span>,<span style="color: red;">1</span><span style="color: green;">&#41;</span><span style="color: green;">&#93;</span>
&nbsp;</pre>
<p>This lets us update potentially nested structures where something may or may not be present , which was fairly tedious to do with earlier lens representations.</p>
<p>Both the former map-like example and the latter update-like behavior were commonly used examples in calls for partial lenses or 'multi-lenses', but here they are able to implemented using a restricted form of a more traditional lens type, and moreover they compose cleanly with other lenses and lens families.</p>
<h2>Rank-1 Lens Families</h2>
<p>At the very start I mentioned that you can dispense with the need for Rank-2 Types. Doing so requires much more tedious type signatures as the <code>LensFamily</code>, <code>Getter</code>, <code>Setter</code> and <code>Lens</code> aliases are no longer legal. Also, if you want to take a lens as an argument and use it in multiple contexts (e.g. as both a getter and a setter), you'll need to clone it to obtain a lens family. For example, this fails:</p>
<pre class="haskell">&nbsp;
ghci&gt; :t \l y -&gt; l ^= y ^. l + <span style="color: red;">1</span> $ y
&lt;interactive&gt;:<span style="color: red;">1</span>:<span style="color: red;">19</span>:
    Couldn't match expected <span style="color: #06c; font-weight: bold;">type</span> `Getting d0 d1'
                with actual <span style="color: #06c; font-weight: bold;">type</span> `Setting d0'
    Expected <span style="color: #06c; font-weight: bold;">type</span>: <span style="color: green;">&#40;</span>d0 -&gt; Getting d0 d1<span style="color: green;">&#41;</span> -&gt; a1 -&gt; Getting d0 b1
      Actual <span style="color: #06c; font-weight: bold;">type</span>: <span style="color: green;">&#40;</span>d0 -&gt; Setting d0<span style="color: green;">&#41;</span> -&gt; a0 -&gt; Setting b0
    In the second argument <span style="color: #06c; font-weight: bold;">of</span> `<span style="color: green;">&#40;</span>^.<span style="color: green;">&#41;</span>', namely `l'
    In the first argument <span style="color: #06c; font-weight: bold;">of</span> `<span style="color: green;">&#40;</span>+<span style="color: green;">&#41;</span>', namely `y ^. l'
&lt;/interactive&gt;</pre>
<p>But we can clone the supplied monomorphic lens using the composition of <code>dlens</code> and <code>plens</code> above, since the <code>DataLensFamily</code> completely characterizes the <code>LensFamily</code> with:</p>
<pre class="haskell">&nbsp;
clone ::
  <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>c -&gt; Store c d d<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>a -&gt; Store c d b<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> -&gt;
  LensFamily a b c d
clone l f a = <span style="color: #06c; font-weight: bold;">case</span> l <span style="color: green;">&#40;</span>Store <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a><span style="color: green;">&#41;</span> a <span style="color: #06c; font-weight: bold;">of</span>
  Store g c -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> g <span style="color: green;">&#40;</span>f c<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>and then the following code type checks:</p>
<pre class="haskell">&nbsp;
ghci&gt; :t \l y -&gt; clone l ^= y ^. clone l + <span style="color: red;">1</span> $ y
\l y -&gt; clone l ^= y ^. clone l + <span style="color: red;">1</span> $ y
  :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="background-color: #efefbf; font-weight: bold;">Num</span></a> d =&gt; <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>c -&gt; Store c d1 d1<span style="color: green;">&#41;</span> -&gt; a -&gt; Store d d b<span style="color: green;">&#41;</span> -&gt; a -&gt; b
&nbsp;</pre>
<p>This means you could implement an entire library to deal with lens families with restricted getters and setters and remain within the confines of Haskell 98. However, the type signatures are considerably less elegant than what becomes available when you simply add Rank2Types.</p>
<h2>Conclusion</h2>
<p>So, we've demonstrated that van Laarhoven lens families let you have lenses that permit polymorphic update, let you offer lenses that are restricted to only allowing the use of getters, setters or modifiers, while granting you easy composition with the existing <code>(.)</code> and <code>id</code> from the <code>Prelude</code>.</p>
<p>I think the practical existence and power of these combinators make a strong case for their use in any serious record reform proposal.</p>
<p>My thanks go to Russell O'Connor. He first noticed that you can generalize van Laarhoven lenses and proposed the <code>clone</code> combinator as a path to Haskell 98/2010 compatibility, while retaining the nicer composition model.</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2012/mirrored-lenses/feed/</wfw:commentRss>
		<slash:comments>491</slash:comments>
		</item>
		<item>
		<title>Searching Infinity Parametrically</title>
		<link>http://comonad.com/reader/2011/searching-infinity/</link>
		<comments>http://comonad.com/reader/2011/searching-infinity/#comments</comments>
		<pubDate>Sun, 25 Dec 2011 06:19:43 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Kan Extensions]]></category>
		<category><![CDATA[Logic]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Monads]]></category>
		<category><![CDATA[Type Hackery]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=510</guid>
		<description><![CDATA[Andrej Bauer recently gave a really nice talk on how you can exploit side-effects to make a faster version of Martin Escardo's pseudo-paradoxical combinators. 
A video of his talk is available over on his blog, and his presentation is remarkably clear, and would serve as a good preamble to the code I'm going to present [...]]]></description>
			<content:encoded><![CDATA[<p>Andrej Bauer recently gave a really nice talk on how you can exploit side-effects to make a faster version of Martin Escardo's pseudo-paradoxical combinators. </p>
<p><a href="http://math.andrej.com/2011/12/06/how-to-make-the-impossible-functionals-run-even-faster/">A video of his talk is available over on his blog</a>, and his presentation is remarkably clear, and would serve as a good preamble to the code I'm going to present below.</p>
<p>Andrej gave a related invited talk back at <a href="http://msfp.org.uk/">MSFP 2008</a> in Iceland, and afterwards over lunch I cornered him (with Dan Piponi) and explained how you could use parametricity to close over the side-effects of monads (or arrows, etc) but I think that trick was lost in the chaos of the weekend, so I've chosen to resurrect it here, and improve it to handle some of his more recent performance enhancements, and show that you don't need side-effects to speed up the search after all!</p>
<p><span id="more-510"></span></p>
<p>First, we'll need to import a few things:</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">{-# LANGUAGE RankNTypes #-}</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">import</span> Data.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Maybe"><span style="background-color: #efefbf; font-weight: bold;">Maybe</span></a> <span style="color: green;">&#40;</span>fromMaybe<span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">import</span> Control.Applicative
<span style="color: #06c; font-weight: bold;">import</span> Data.IntMap <span style="color: green;">&#40;</span>IntMap<span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">import</span> <span style="color: #06c; font-weight: bold;">qualified</span> Data.IntMap <span style="color: #06c; font-weight: bold;">as</span> IntMap
<span style="color: #06c; font-weight: bold;">import</span> Control.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a>
<span style="color: #06c; font-weight: bold;">import</span> Control.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a>.Trans.Class
<span style="color: #06c; font-weight: bold;">import</span> Data.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a>.Identity
&nbsp;</pre>
<p>What are looking for is an implementation of <a href="http://en.wikipedia.org/wiki/Epsilon_calculus">Hilbert's epsilon</a>. </p>
<p>This is a formal mechanism for eliminating existentials over some non-empty set <strong>X</strong> by defining a function</p>
<pre class="haskell">&nbsp;
ε: <span style="color: green;">&#40;</span>X -&gt; Prop<span style="color: green;">&#41;</span> -&gt; X
&nbsp;</pre>
<p>such that if there exists an <em>x</em> in <strong>X</strong> such that <em>p</em>(<strong>X</strong>) holds then <em>p</em>(<em>ε</em>(<em>p</em>)) holds.</p>
<p>As noted by Andrej, we could reify this constructively as a function "epsilon :: (X -> Bool) -> X" for some X.</p>
<p>Now, for some sets, Hilbert's epsilon is really easy to define. If X is a finite set, you can just exhaustively enumerate all of the options returning a member of X such that the property holds if any of them do, otherwise since X is non-empty, just return one of the elements that you tested.</p>
<p>This would be a pretty boring article and I'd be back to eating Christmas dinner with my family if that was all there was to it. However, certain infinite spaces can also be searched.</p>
<p>Last year, Luke Palmer wrote a post on <a href="http://lukepalmer.wordpress.com/2010/11/17/searchable-data-types/">"Searchable Data Types"</a> that might also serve as a good introduction. In that article he led off with the easiest infinite space to search, the lazy naturals, or the 'one point compactification of the naturals'. That is to say the natural numbers extended with infinity.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> LazyNat = Zero | Succ LazyNat
infinity :: LazyNat
infinity = Succ infinity
&nbsp;</pre>
<p>Now we can implement Palmer's epsilon (called <code>lyingSearch</code> in his article).</p>
<pre class="haskell">&nbsp;
palmer :: <span style="color: green;">&#40;</span>LazyNat -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> -&gt; LazyNat
palmer p
  | p Zero = Zero
  | <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:otherwise"><span style="font-weight: bold;">otherwise</span></a> = Succ $ palmer $ p . Succ
&nbsp;</pre>
<p>The trick to making this work is that we place a requirement that the predicate that you pass has to terminate in a bounded amount of time no matter what input you give it, and since we're working with the naturals extended with <code>infinity</code>, if no natural satisfies the predicate, we'll just keep returning a longer and longer chain of <code>Succ</code>'s, effectively yielding <code>infinity</code>. </p>
<p>To check to see if the returned number satisfies the predicate you can always use <code>p (palmer p)</code>. The predicate is required to terminate in finite time, even when given infinity, so this will yield a Bool and not bottom out unless the user supplied predicate takes an unbounded amount of time.</p>
<p>I posted a reply to Luke's article when it came up on reddit which included a Hinze-style generic implementation of his <code>lyingSearch</code> predicate, which you can see now is just Hilbert's epsilon for arbitrary recursive polynomial data types.</p>
<p><a href="http://www.reddit.com/r/haskell/comments/e7nij/searchable_data_types/c15zs6l">http://www.reddit.com/r/haskell/comments/e7nij/searchable_data_types/c15zs6l</a></p>
<p>Another space we can search is <a href="http://en.wikipedia.org/wiki/Cantor_space">the Cantor space</a> 2^N.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Cantor = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Integer"><span style="background-color: #efefbf; font-weight: bold;">Integer</span></a> -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a>
&nbsp;</pre>
<p>With that we jump clear from countable infinity to uncountable infinity, but it can still be searched in finite time!</p>
<p>This is the space we'll be paying attention to for the rest of this article.</p>
<p>First we'll define how to "<a href="http://en.wikipedia.org/wiki/Hilbert's_paradox_of_the_Grand_Hotel">book a room in Hilbert's Hotel</a>."</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">infixr</span> <span style="color: red;">0</span> #
<span style="color: green;">&#40;</span>#<span style="color: green;">&#41;</span> :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a> -&gt; Cantor -&gt; Cantor
<span style="color: green;">&#40;</span>x # a<span style="color: green;">&#41;</span> <span style="color: red;">0</span> = x
<span style="color: green;">&#40;</span>x # a<span style="color: green;">&#41;</span> i = a <span style="color: green;">&#40;</span>i - <span style="color: red;">1</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Then this can be used to obtain the following implementation of Hilbert's epsilon for the Cantor space, attributed by Andrej to Ulrich Berger.</p>
<pre class="haskell">&nbsp;
berger :: <span style="color: green;">&#40;</span>Cantor -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> -&gt; Cantor
berger p =
  <span style="color: #06c; font-weight: bold;">if</span> ex $ \a -&gt; p $ <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a> # a
  <span style="color: #06c; font-weight: bold;">then</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a> # berger $ \a -&gt; p $ <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a> # a
  <span style="color: #06c; font-weight: bold;">else</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:True"><span style="font-weight: bold;">True</span></a>  # berger $ \a -&gt; p $ <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:True"><span style="font-weight: bold;">True</span></a> # a
  <span style="color: #06c; font-weight: bold;">where</span> ex q = q <span style="color: green;">&#40;</span>berger q<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>This version is particularly close in structure to the one for searching the LazyNats, but it is dreadfully slow!</p>
<p>It would be nice to be able to search the space faster and that is just what Martin Escardo's improved version does, through a more sophisticated divide and conquer technique.</p>
<pre class="haskell">&nbsp;
escardo :: <span style="color: green;">&#40;</span>Cantor -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> -&gt; Cantor
escardo p = go x l r <span style="color: #06c; font-weight: bold;">where</span>
  go x l r n =  <span style="color: #06c; font-weight: bold;">case</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:divMod"><span style="font-weight: bold;">divMod</span></a> n <span style="color: red;">2</span> <span style="color: #06c; font-weight: bold;">of</span>
    <span style="color: green;">&#40;</span><span style="color: red;">0</span>, <span style="color: red;">0</span><span style="color: green;">&#41;</span> -&gt; x
    <span style="color: green;">&#40;</span>q, <span style="color: red;">1</span><span style="color: green;">&#41;</span> -&gt; l q
    <span style="color: green;">&#40;</span>q, <span style="color: red;">0</span><span style="color: green;">&#41;</span> -&gt; r $ q<span style="color: red;">-1</span>
  x = ex $ \l -&gt; ex $ \r -&gt; p $ go <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:True"><span style="font-weight: bold;">True</span></a> l r
  l = escardo $ \l -&gt; ex $ \r -&gt; p $ go x l r
  r = escardo $ \r -&gt; p $ go x l r
  ex q = q <span style="color: green;">&#40;</span>escardo q<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>To proceed from here I'll need a State monad:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> S s a = S <span style="color: green;">&#123;</span> runS :: s -&gt; <span style="color: green;">&#40;</span>a, s<span style="color: green;">&#41;</span> <span style="color: green;">&#125;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>S s<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>S m<span style="color: green;">&#41;</span> = S $ \s -&gt; <span style="color: #06c; font-weight: bold;">case</span> m s <span style="color: #06c; font-weight: bold;">of</span>
    <span style="color: green;">&#40;</span>a, s'<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>f a, s'<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Applicative <span style="color: green;">&#40;</span>S s<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  pure = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a>
  <span style="color: green;">&#40;</span>&lt; *&gt;<span style="color: green;">&#41;</span> = ap
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> <span style="color: green;">&#40;</span>S m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> a = S $ \s -&gt; <span style="color: green;">&#40;</span>a, s<span style="color: green;">&#41;</span>
  S m &gt;&gt;= k = S $ \s -&gt; <span style="color: #06c; font-weight: bold;">case</span> m s <span style="color: #06c; font-weight: bold;">of</span>
    <span style="color: green;">&#40;</span>a, s'<span style="color: green;">&#41;</span> -&gt; runS <span style="color: green;">&#40;</span>k a<span style="color: green;">&#41;</span> s'
&nbsp;</pre>
<p>And now we've reached the point. From here,  Andrej's pure code ends, and his side-effecting ocaml and custom programming language start. The first thing he does is compute the modulus of continuity by using a side-effect that writes to a reference cell which he very carefully ensures doesn't leak out of scope, so he doesn't have to concern himself with the proposition code editing the value of the reference.</p>
<pre class="ocaml">&nbsp;
<span style="color: #06c; font-weight: bold;">let</span> mu f a =
  <span style="color: #06c; font-weight: bold;">let</span> r = <span style="color: #06c; font-weight: bold;">ref</span> <span style="color: #c6c;">0</span> <span style="color: #06c; font-weight: bold;">in</span>
  <span style="color: #06c; font-weight: bold;">let</span> b n = <span style="color: #6c6;">&#40;</span>r := <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html#VALmax"><span style="">max</span></a> n ! r; a n<span style="color: #6c6;">&#41;</span> <span style="color: #06c; font-weight: bold;">in</span>
    <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html#VALignore"><span style="">ignore</span></a> <span style="color: #6c6;">&#40;</span>f b<span style="color: #6c6;">&#41;</span>;
    !r
&nbsp;</pre>
<p>To obtain the same effect we'll instead make a predicate using the state monad to model the single reference cell. </p>
<pre lang="haskell'>
modulus phi alpha = snd $ runS (phi beta) 0 where
  beta n = S $ \ i -> (alpha n, max i n)
</pre>
<p>But now, we've lost the safety that was implied by the local lexical scope. If we let the type checker give us a type we obtain:</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- bad</span>
modulus :: <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="background-color: #efefbf; font-weight: bold;">Num</span></a> b, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="background-color: #efefbf; font-weight: bold;">Ord</span></a> s<span style="color: green;">&#41;</span> =&gt;
  <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>s -&gt; S s a<span style="color: green;">&#41;</span> -&gt; S b c<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>s -&gt; a<span style="color: green;">&#41;</span> -&gt; b
&nbsp;</pre>
<p>We can mash b and s together, and try to make the ordering and number agree by claiming that it is instead Real and we'd get the slightly more reasonable looking type:</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- still bad</span>
modulus :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Real"><span style="background-color: #efefbf; font-weight: bold;">Real</span></a> a =&gt;
  <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>a -&gt; S n b<span style="color: green;">&#41;</span> -&gt; S n c<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>a -&gt; b<span style="color: green;">&#41;</span> -&gt; a
&nbsp;</pre>
<p>In the imperative code, lexical scoping had ensured that no other code could edit the reference cell, but with this type we don't have that. The predicate is allowed to use arbitrary state actions to muck with the modulus of convergence even though the only thing that should be editing it is the wrapper beta that we placed around alpha.</p>
<p>But how can we ensure that the end user couldn't gain access to any of the additional functionality from the monad? Parametricity!</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- getting better</span>
modulus :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Real"><span style="background-color: #efefbf; font-weight: bold;">Real</span></a> a =&gt;
  <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> f. <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> f =&gt; <span style="color: green;">&#40;</span>a -&gt; f b<span style="color: green;">&#41;</span> -&gt; f c<span style="color: green;">&#41;</span> -&gt;
  <span style="color: green;">&#40;</span>a -&gt; b<span style="color: green;">&#41;</span> -&gt;
  a
&nbsp;</pre>
<p>Here the only thing you are allowed to assume about f is that it forms a monad. This gives you access to return and >>=, but the predicate can't do anything interesting with them. All it can do is work with what is effectively the identity monad, since it knows no additional properties!</p>
<p>We can have mercy on the end user and give them a little bit more syntactic sugar, since it doesn't cost us anything to let them also have access to the Applicative instance.</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- good</span>
modulus :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Real"><span style="background-color: #efefbf; font-weight: bold;">Real</span></a> a =&gt;
  <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> f. <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> f, Applicative f<span style="color: green;">&#41;</span> =&gt; <span style="color: green;">&#40;</span>a -&gt; f b<span style="color: green;">&#41;</span> -&gt; f c<span style="color: green;">&#41;</span> -&gt;
  <span style="color: green;">&#40;</span>a -&gt; b<span style="color: green;">&#41;</span> -&gt;
  a
&nbsp;</pre>
<p>With that we can show Andrej's version of the modulus of convergence calculation does not need side-effects!</p>
<pre class="haskell">&gt;
&gt; modulus <span style="color: green;">&#40;</span>\a -&gt; a <span style="color: red;">10</span> &gt;&gt;= a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>\n -&gt; n * n<span style="color: green;">&#41;</span>
<span style="color: red;">100</span>
&nbsp;</pre>
<p>Admittedly plumbing around the monadic values in our proposition is a bit inconvenient.</p>
<p>His next example was written in a custom ocaml-like programming language. For translating his effect type into Haskell using parametricity, we'll need a CPS'd state monad, so we can retry from the current continuation while we track a map of assigned values.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> K r s a = K <span style="color: green;">&#123;</span> runK :: <span style="color: green;">&#40;</span>a -&gt; s -&gt; r<span style="color: green;">&#41;</span> -&gt; s -&gt; r <span style="color: green;">&#125;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>K r s<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> = liftM
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Applicative <span style="color: green;">&#40;</span>K r s<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  pure = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a>
  <span style="color: green;">&#40;</span>&lt; *&gt;<span style="color: green;">&#41;</span> = ap
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> <span style="color: green;">&#40;</span>K r s<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> a = K $ \k -&gt; k a
  K m &gt;&gt;= f = K $ \k -&gt; m $ \a -&gt; runK <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span> k
&nbsp;</pre>
<p>For those of you who have been paying attention to my previous posts, <code>K r s</code> is just a <code>Codensity</code> monad!</p>
<pre class="haskell">&nbsp;
neighborhood ::
  <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> f. <span style="color: green;">&#40;</span>Applicative f, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> f<span style="color: green;">&#41;</span> =&gt; <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="background-color: #efefbf; font-weight: bold;">Int</span></a> -&gt; f <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> -&gt; f <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> -&gt;
  IntMap <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a>
neighborhood phi = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:snd"><span style="font-weight: bold;">snd</span></a> $ runK <span style="color: green;">&#40;</span>phi beta<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>,<span style="color: green;">&#41;</span> IntMap.empty <span style="color: #06c; font-weight: bold;">where</span>
  beta n = K $ \k s -&gt; <span style="color: #06c; font-weight: bold;">case</span> IntMap.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:lookup"><span style="font-weight: bold;">lookup</span></a> n s <span style="color: #06c; font-weight: bold;">of</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Just"><span style="font-weight: bold;">Just</span></a> b -&gt; k b s
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Nothing"><span style="font-weight: bold;">Nothing</span></a> -&gt; <span style="color: #06c; font-weight: bold;">case</span> k <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:True"><span style="font-weight: bold;">True</span></a> <span style="color: green;">&#40;</span>IntMap.insert n <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:True"><span style="font-weight: bold;">True</span></a> s<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">of</span>
      <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a>, _<span style="color: green;">&#41;</span> -&gt; k <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a> <span style="color: green;">&#40;</span>IntMap.insert n <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a> s<span style="color: green;">&#41;</span>
      r -&gt; r
&nbsp;</pre>
<p>With that we can adapt the final version of Hilbert's epsilon for the Cantor space that Andrej provided to run in pure Haskell.</p>
<pre class="haskell">&nbsp;
bauer ::
  <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> f. <span style="color: green;">&#40;</span>Applicative f, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> f<span style="color: green;">&#41;</span> =&gt; <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="background-color: #efefbf; font-weight: bold;">Int</span></a> -&gt; f <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> -&gt; f <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> -&gt;
  Cantor
bauer p = \n -&gt; fromMaybe <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:True"><span style="font-weight: bold;">True</span></a> $ IntMap.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:lookup"><span style="font-weight: bold;">lookup</span></a> n m <span style="color: #06c; font-weight: bold;">where</span>
  m = neighborhood p
&nbsp;</pre>
<p>With a little work you can implement a version of an exists and forAll predicate on top of that by running them through the identity monad. </p>
<pre class="haskell">&nbsp;
exists ::
  <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> f. <span style="color: green;">&#40;</span>Applicative f, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> f<span style="color: green;">&#41;</span> =&gt; <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="background-color: #efefbf; font-weight: bold;">Int</span></a> -&gt; f <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> -&gt; f <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> -&gt;
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a>
forAll ::
  <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> f. <span style="color: green;">&#40;</span>Applicative f, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> f<span style="color: green;">&#41;</span> =&gt; <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="background-color: #efefbf; font-weight: bold;">Int</span></a> -&gt; f <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> -&gt; f <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> -&gt;
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a>
&nbsp;</pre>
<p>I've gone further in playing with this idea, using monad homomorphisms rather than simply relying on the canonical homomorphism from the identity monad. You can get the gist of it here:</p>
<p><a href="https://gist.github.com/1518767">https://gist.github.com/1518767</a></p>
<p>This permits the predicates themselves to embed some limited monadic side-effects, but then you get more extensional vs. intensional issues.</p>
<p>An obvious direction from here is to fiddle with a version of Martin Escardo's search monad that takes advantage of these techniques, but I'll leave the exploration of these ideas to the reader for now and go enjoy Christmas dinner.</p>
<p>Happy Holidays,<br />
Edward Kmett</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2011/searching-infinity/feed/</wfw:commentRss>
		<slash:comments>395</slash:comments>
		</item>
		<item>
		<title>A Parsec Full of Rats, Part 2</title>
		<link>http://comonad.com/reader/2011/a-parsec-full-of-rats-part-2/</link>
		<comments>http://comonad.com/reader/2011/a-parsec-full-of-rats-part-2/#comments</comments>
		<pubDate>Sat, 24 Sep 2011 03:07:32 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Monads]]></category>
		<category><![CDATA[Parsing]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[packrat]]></category>
		<category><![CDATA[parsec]]></category>
		<category><![CDATA[trifecta]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=397</guid>
		<description><![CDATA[Last time, I showed that we can build a small parsec clone with packrat support.
This time I intend to implement packrat directly on top of Parsec 3.
One of the main topics of discussion when it comes to packrat parsing since Bryan Ford's initial release of Pappy has been the fact that in general you shouldn't [...]]]></description>
			<content:encoded><![CDATA[<p>Last time, I showed that we can build a small parsec clone with packrat support.</p>
<p>This time I intend to implement packrat directly on top of Parsec 3.</p>
<p>One of the main topics of discussion when it comes to packrat parsing since Bryan Ford's initial release of Pappy has been the fact that in general you shouldn't use packrat to memoize every rule, and that instead you should apply Amdahl's law to look for the cases where the lookup time is paid back in terms of repetitive evaluation, computation time and the hit rate. This is great news for us, since, we only want to memoize a handful of expensive combinators.</p>
<p><span id="more-397"></span></p>
<p>First, we'll need to import enough of Parsec to do something interesting.</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">{-# LANGUAGE RecordWildCards, ViewPatterns, FlexibleInstances, MultiParamTypeClasses #-}</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">import</span> Text.Parsec
<span style="color: #06c; font-weight: bold;">import</span> <span style="color: #06c; font-weight: bold;">qualified</span> Text.Parsec.Token <span style="color: #06c; font-weight: bold;">as</span> T
<span style="color: #06c; font-weight: bold;">import</span> Text.Parsec.Token
    <span style="color: green;">&#40;</span>GenLanguageDef<span style="color: green;">&#40;</span>..<span style="color: green;">&#41;</span>, GenTokenParser<span style="color: green;">&#40;</span>TokenParser<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">import</span> Text.Parsec.Pos <span style="color: green;">&#40;</span>initialPos, updatePosChar<span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">import</span> Data.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a>.Identity <span style="color: green;">&#40;</span>Identity<span style="color: green;">&#40;</span>..<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">import</span> Control.Applicative <span style="color: #06c; font-weight: bold;">hiding</span> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>&lt; |&gt;<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">import</span> Control.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a>.Fix <span style="color: green;">&#40;</span>fix<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Then as before, we'll define PEG-style backtracking:</p>
<pre class="haskell">&nbsp;
<span style="color: green;">&#40;</span>&lt; /&gt;<span style="color: green;">&#41;</span> :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m =&gt; ParsecT s u m a -&gt; ParsecT s u m a -&gt;
    ParsecT s u m a
p &lt; /&gt; q = try p &lt; |&gt; q
<span style="color: #06c; font-weight: bold;">infixl</span> <span style="color: red;">3</span> &lt; /&gt;
&nbsp;</pre>
<p>Now we need an analogue to our Result type from last time, which recalled whether or not we had consumed input, and what the current cursor location is. Fortunately, we can recycle the definitions from Parsec to this end.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Result d a = Consumed <span style="color: green;">&#40;</span>Reply d <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> a<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>We'll define a combinator to build a parser directly from a field accessor. Last time, this was just the use of the "Rat" constructor. Now it is a bit trickier, because we need to turn <code>Consumed (Reply d () a)</code> into <code>m (Consumed (m (Reply d u a)))</code> by wrapping it in the appropriate monad, and giving the user back his state unmolested. </p>
<pre class="haskell">&nbsp;
rat :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m =&gt; <span style="color: green;">&#40;</span>d -&gt; Result d a<span style="color: green;">&#41;</span> -&gt; ParsecT d u m a
rat f   = mkPT $ \s0 -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> $
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> . patch s0 &lt; $&gt; f <span style="color: green;">&#40;</span>stateInput s0<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  patch <span style="color: green;">&#40;</span>State _ _ u<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>Ok a <span style="color: green;">&#40;</span>State s p _<span style="color: green;">&#41;</span> err<span style="color: green;">&#41;</span> = Ok a <span style="color: green;">&#40;</span>State s p u<span style="color: green;">&#41;</span> err
  patch _             <span style="color: green;">&#40;</span>Error e<span style="color: green;">&#41;</span>                = Error e
&nbsp;</pre>
<p>Last time we could go from a parser to a result just by applying the user stream type, but with parsec we also have to supply their notion of a position. This leads to the following combinator. By running in the Identity monad with no user state it should be obvious that we've duplicated the functionality of the previous 'Rat' parser (with the addition of a source position).</p>
<pre class="haskell">&nbsp;
womp :: d -&gt; SourcePos -&gt; ParsecT d <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> Identity a -&gt; Result d a
womp d pos p = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> runIdentity . runIdentity $
    runParsecT p <span style="color: green;">&#40;</span>State d pos <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>The combinator is so named because we needed a big space-rat rather than a little pack-rat to keep with the theme.</p>
<blockquote><p>It's not impossible. I used to bullseye womp rats in my T-16 back home, they're not much bigger than two meters.</p></blockquote>
<p>Now we'll write a bit of annoyingly verbose boilerplate to convince <code>Parsec</code> that we really want a <code>LanguageDef</code> for some monad other than Identity. (As an aside, why <code>Text.Parsec.Language</code> doesn't contain GenLanguageDefs that are parametric in their choice of Monad is beyond me.) </p>
<pre class="haskell">&nbsp;
myLanguageDef :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m =&gt; T.GenLanguageDef D u m
myLanguageDef = T.LanguageDef
  <span style="color: green;">&#123;</span> commentStart    = <span style="color: #3c7331;">&quot;{-&quot;</span>
  , commentEnd      = <span style="color: #3c7331;">&quot;-}&quot;</span>
  , commentLine     = <span style="color: #3c7331;">&quot;--&quot;</span>
  , nestedComments  = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:True"><span style="font-weight: bold;">True</span></a>
  , identStart      = letter &lt; |&gt; char '_'
  , identLetter     = alphaNum &lt; |&gt; oneOf <span style="color: #3c7331;">&quot;_'&quot;</span>
  , opStart         = opLetter myLanguageDef
  , opLetter        = oneOf <span style="color: #3c7331;">&quot;:!#$%&amp;*+./&lt; =&gt;?@<span style="">\\</span>^|-~&quot;</span>
  , reservedOpNames = <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span>
  , reservedNames   = <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span>
  , caseSensitive   = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:True"><span style="font-weight: bold;">True</span></a>
  <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>As a shameless plug, trifecta offers a particularly nice solution to this problem, breaking up the monolithic Token type into separate concerns and letting you layer parser transformers that enrich the parser to deal with things like Haskell-style layout, literate comments, parsing comments in whitespace, etc. </p>
<p>And as one last bit of boilerplate, we'll abuse RecordWildcards once again to avoid the usual 20 lines of boilerplate that are expected of us, so we can get access to parsec's token parsers.</p>
<pre class="haskell">&nbsp;
TokenParser <span style="color: green;">&#123;</span>..<span style="color: green;">&#125;</span> = T.makeTokenParser myLanguageDef
&nbsp;</pre>
<p>Now we're ready to define our incredibly straightforward stream type:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> D = D
  <span style="color: green;">&#123;</span> _add        :: Result D <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Integer"><span style="background-color: #efefbf; font-weight: bold;">Integer</span></a>
  , _mult       :: Result D <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Integer"><span style="background-color: #efefbf; font-weight: bold;">Integer</span></a>
  , _primary    :: Result D <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Integer"><span style="background-color: #efefbf; font-weight: bold;">Integer</span></a>
  , _dec        :: Result D <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Integer"><span style="background-color: #efefbf; font-weight: bold;">Integer</span></a>
  , _uncons     :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Maybe"><span style="background-color: #efefbf; font-weight: bold;">Maybe</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Char"><span style="background-color: #efefbf; font-weight: bold;">Char</span></a>, D<span style="color: green;">&#41;</span>
  <span style="color: green;">&#125;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m =&gt; Stream D m <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Char"><span style="background-color: #efefbf; font-weight: bold;">Char</span></a> <span style="color: #06c; font-weight: bold;">where</span>
  uncons = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> . _uncons
&nbsp;</pre>
<p>And using the general purpose <code>rat</code> combinator from earlier, we can write some memoized parsers:</p>
<pre class="haskell">&nbsp;
add, mult, primary, dec :: Parsec D u <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Integer"><span style="background-color: #efefbf; font-weight: bold;">Integer</span></a>
add     = rat _add
mult    = rat _mult
primary = rat _primary
dec     = rat _dec
&nbsp;</pre>
<p>And finally, we write the code to tie the knot and build the stream:</p>
<pre class="haskell">&nbsp;
parse :: SourceName -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="background-color: #efefbf; font-weight: bold;">String</span></a> -&gt; D
parse n = go <span style="color: green;">&#40;</span>initialPos n<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  go p s = fix $ \d -&gt; <span style="color: #06c; font-weight: bold;">let</span>
    <span style="color: green;">&#40;</span>womp d p -&gt; _add<span style="color: green;">&#41;</span> =
            <span style="color: green;">&#40;</span>+<span style="color: green;">&#41;</span> &lt; $&gt; mult &lt; * reservedOp <span style="color: #3c7331;">&quot;+&quot;</span> &lt;*&gt; add
        &lt; /&gt; mult &lt; ?&gt; <span style="color: #3c7331;">&quot;summand&quot;</span>
    <span style="color: green;">&#40;</span>womp d p -&gt; _mult<span style="color: green;">&#41;</span> =
            <span style="color: green;">&#40;</span>*<span style="color: green;">&#41;</span> &lt; $&gt; primary &lt; * reservedOp <span style="color: #3c7331;">&quot;*&quot;</span> &lt;*&gt; mult
        &lt; /&gt; primary &lt; ?&gt; <span style="color: #3c7331;">&quot;factor&quot;</span>
    <span style="color: green;">&#40;</span>womp d p -&gt; _primary<span style="color: green;">&#41;</span> =
            parens add
        &lt; /&gt; dec &lt; ?&gt; <span style="color: #3c7331;">&quot;number&quot;</span>
    <span style="color: green;">&#40;</span>womp d p -&gt; _dec<span style="color: green;">&#41;</span> = natural
    _uncons = <span style="color: #06c; font-weight: bold;">case</span> s <span style="color: #06c; font-weight: bold;">of</span>
      <span style="color: green;">&#40;</span>x:xs<span style="color: green;">&#41;</span> -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Just"><span style="font-weight: bold;">Just</span></a> <span style="color: green;">&#40;</span>x, go <span style="color: green;">&#40;</span>updatePosChar p x<span style="color: green;">&#41;</span> xs<span style="color: green;">&#41;</span>
      <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span>     -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Nothing"><span style="font-weight: bold;">Nothing</span></a>
    <span style="color: #06c; font-weight: bold;">in</span> D <span style="color: green;">&#123;</span> .. <span style="color: green;">&#125;</span>
&nbsp;
runD :: Parsec D u a -&gt; u -&gt; SourceName -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="background-color: #efefbf; font-weight: bold;">String</span></a> -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="background-color: #efefbf; font-weight: bold;">Either</span></a> ParseError a
runD p u fn s = runParser p u fn <span style="color: green;">&#40;</span>prep fn s<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>and finally, let it rip:</p>
<pre class="haskell">&nbsp;
eval :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="background-color: #efefbf; font-weight: bold;">String</span></a> -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Integer"><span style="background-color: #efefbf; font-weight: bold;">Integer</span></a>
eval s = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:either"><span style="font-weight: bold;">either</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:error"><span style="font-weight: bold;">error</span></a> . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:show"><span style="font-weight: bold;">show</span></a><span style="color: green;">&#41;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a> $
    runD <span style="color: green;">&#40;</span>whiteSpace *&gt; add &lt; * eof<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> <span style="color: #3c7331;">&quot;-&quot;</span> s
&nbsp;</pre>
<p>While this approach tends to encourage memoizing fewer combinators than libraries such as frisby, this is exactly what <a href="http://www.mercury.csse.unimelb.edu.au/information/papers/packrat.pdf">current research suggests you probably should do</a> with packrat parsing!</p>
<p>The other purported advantage of packrat parsers is that they <a href="http://www.vpri.org/pdf/tr2007002_packrat.pdf">can deal with left recursion in the grammar</a>. However, that is not the case, hidden left recursion in the presence of the algorithm used in the scala parsing combinator libraries leads to incorrect non-left-most parses <a href="http://tratt.net/laurie/research/publications/papers/tratt__direct_left_recursive_parsing_expression_grammars.pdf">as shown by Tratt</a>.</p>
<p>I leave it as an exercise for the reader to extend this material with the parsec+iteratees approach from my original talk on trifecta to get packrat parsing of streaming input. Either that or you can wait until it is integrated into trifecta.</p>
<p>You can download the source to this (without the spurious spaces inserted by wordpress) <a href="https://github.com/ekmett/trifecta/blob/master/wip/Womprat.hs">here</a>.</p>
<p>If I can find the time, I hope to spend some time addressing Scott and Johnstone's GLL parsers, which actually achieve the O(n^3) worst case bounds touted for Tomita's GLR algorithm (which is actually O(n^4) as it was originally defined despite the author's claims), and how to encode them in Haskell with an eye towards building a memoizing parser combinator library that can parse LL(1) fragments in O(1), deal with arbitrary context-free grammars in O(n^3), and degrade reasonably gracefully in the presence of context-sensitivity, while supporting hidden left recursion as long as such recursion passes through at least one memoized rule. This is important because CFGs are closed under extensions to the grammar, which is a nice property to have if you want to have a language where you can add new statement types easily without concerning yourself overmuch with the order in which you insert the rules or load the different extensions.</p>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2011/a-parsec-full-of-rats-part-2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>A Parsec Full of Rats, Part 1</title>
		<link>http://comonad.com/reader/2011/a-parsec-full-of-rats/</link>
		<comments>http://comonad.com/reader/2011/a-parsec-full-of-rats/#comments</comments>
		<pubDate>Sat, 24 Sep 2011 02:10:06 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Monads]]></category>
		<category><![CDATA[Parsing]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[packrat]]></category>
		<category><![CDATA[trifecta]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=380</guid>
		<description><![CDATA[You never heard of the Millenium Falcon? It's the ship that made the Kessel Run in 12 parsecs.
I've been working on a parser combinator library called trifecta, and so I decided I'd share some thoughts on parsing. 
Packrat parsing (as provided by frisby, pappy, rats! and the Scala parsing combinators) and more traditional recursive descent [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p>You never heard of the Millenium Falcon? It's the ship that made the Kessel Run in 12 parsecs.</p></blockquote>
<p>I've been working on a parser combinator library called <a href="http://hackage.haskell.org/package/trifecta">trifecta</a>, and so I decided I'd share some thoughts on parsing. </p>
<p><a href="http://pdos.csail.mit.edu/~baford/packrat/">Packrat parsing</a> (as provided by <a href="http://hackage.haskell.org/package/frisby">frisby</a>, <a href="http://hackage.haskell.org/package/pappy">pappy</a>, <a href="http://cs.nyu.edu/rgrimm/xtc/">rats!</a> and the Scala parsing combinators) and more traditional recursive descent parsers (like Parsec) are often held up as somehow different. </p>
<p>Today I'll show that you can add monadic parsing to a packrat parser, sacrificing asymptotic guarantees in exchange for the convenient context sensitivity, and conversely how you can easily add packrat parsing to a traditional monadic parser combinator library.</p>
<p><span id="more-380"></span></p>
<p>To keep this post self-contained, I'm going to start by defining a small packrat parsing library by hand, which acts rather like parsec in its backtracking behavior. First, some imports:</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">{-# LANGUAGE RecordWildCards, ViewPatterns, DeriveFunctor #-}</span>
<span style="color: #06c; font-weight: bold;">import</span> Control.Applicative
<span style="color: #06c; font-weight: bold;">import</span> Control.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> <span style="color: green;">&#40;</span>MonadPlus<span style="color: green;">&#40;</span>..<span style="color: green;">&#41;</span>, guard<span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">import</span> Control.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a>.Fix <span style="color: green;">&#40;</span>fix<span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">import</span> Data.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Char"><span style="background-color: #efefbf; font-weight: bold;">Char</span></a> <span style="color: green;">&#40;</span>isDigit, digitToInt, isSpace<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Second, we'll define a bog simple parser, which consumes an input stream of type d, yielding a possible answer and telling us whether or not it has actually consumed any input as it went.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Rat d a = Rat <span style="color: green;">&#123;</span> runRat :: d -&gt; Result d a <span style="color: green;">&#125;</span>
  <span style="color: #06c; font-weight: bold;">deriving</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a>
&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Result d a
  = Pure a             <span style="color: #5d478b; font-style: italic;">-- didn't consume anything, can backtrack</span>
  | Commit d a      <span style="color: #5d478b; font-style: italic;">-- consumed input</span>
  | Fail <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="background-color: #efefbf; font-weight: bold;">String</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a> <span style="color: #5d478b; font-style: italic;">-- failed, flagged if consumed</span>
  <span style="color: #06c; font-weight: bold;">deriving</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a>
&nbsp;</pre>
<p>Now, we can finally implement some type classes:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Applicative <span style="color: green;">&#40;</span>Rat d<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  pure a = Rat $ \ _ -&gt; Pure a
  Rat mf &lt; *&gt; Rat ma = Rat $ \ d -&gt; <span style="color: #06c; font-weight: bold;">case</span> mf d <span style="color: #06c; font-weight: bold;">of</span>
    Pure f      -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>ma d<span style="color: green;">&#41;</span>
    Fail s c    -&gt; Fail s c
    Commit d' f -&gt; <span style="color: #06c; font-weight: bold;">case</span> ma d' <span style="color: #06c; font-weight: bold;">of</span>
      Pure a       -&gt; Commit d' <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span>
      Fail s _     -&gt; Fail s <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:True"><span style="font-weight: bold;">True</span></a>
      Commit d'' a -&gt; Commit d'' <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>including an instance of Alternative that behaves like parsec, only backtracking on failure if no input was unconsumed.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Alternative <span style="color: green;">&#40;</span>Rat d<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  Rat ma &lt; |&gt; Rat mb = Rat $ \ d -&gt; <span style="color: #06c; font-weight: bold;">case</span> ma d <span style="color: #06c; font-weight: bold;">of</span>
    Fail _ <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a> -&gt; mb d
    x            -&gt; x
  empty = Rat $ \ _ -&gt; Fail <span style="color: #3c7331;">&quot;empty&quot;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a>
&nbsp;</pre>
<p>For those willing to forego the asymptotic guarantees of packrat, we'll offer a monad.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> <span style="color: green;">&#40;</span>Rat d<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> a = Rat $ \_ -&gt; Pure a
  Rat m &gt;&gt;= k = Rat $ \d -&gt; <span style="color: #06c; font-weight: bold;">case</span> m d <span style="color: #06c; font-weight: bold;">of</span>
    Pure a -&gt; runRat <span style="color: green;">&#40;</span>k a<span style="color: green;">&#41;</span> d
    Commit d' a -&gt; <span style="color: #06c; font-weight: bold;">case</span> runRat <span style="color: green;">&#40;</span>k a<span style="color: green;">&#41;</span> d' <span style="color: #06c; font-weight: bold;">of</span>
      Pure b -&gt; Commit d' b
      Fail s _ -&gt; Fail s <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:True"><span style="font-weight: bold;">True</span></a>
      commit -&gt; commit
    Fail s c -&gt; Fail s c
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fail"><span style="font-weight: bold;">fail</span></a> s = Rat $ \ _ -&gt; Fail s <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> MonadPlus <span style="color: green;">&#40;</span>Rat d<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  mplus = <span style="color: green;">&#40;</span>&lt; |&gt;<span style="color: green;">&#41;</span>
  mzero = empty
&nbsp;</pre>
<p>and a Parsec-style "try", which rewinds on failure, so that < |> can try again.</p>
<pre class="haskell">&nbsp;
try :: Rat d a -&gt; Rat d a
try <span style="color: green;">&#40;</span>Rat m<span style="color: green;">&#41;</span> = Rat $ \d -&gt; <span style="color: #06c; font-weight: bold;">case</span> m d <span style="color: #06c; font-weight: bold;">of</span>
  Fail s _ -&gt; Fail s <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a>
  x        -&gt; x
&nbsp;</pre>
<p>Since we've consumed < |> with parsec semantics. Let's give a PEG-style backtracking (< />).</p>
<pre class="haskell">&nbsp;
<span style="color: green;">&#40;</span>&lt; /&gt;<span style="color: green;">&#41;</span> :: Rat d a -&gt; Rat d a -&gt; Rat d a
p &lt; /&gt; q = try p &lt; |&gt; q
<span style="color: #06c; font-weight: bold;">infixl</span> <span style="color: red;">3</span> &lt; /&gt;
&nbsp;</pre>
<p>So far nothing we have done involves packrat at all. These are all general purpose recursive descent combinators.</p>
<p>We can define an input stream and a number of combinators to read input.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> Stream d <span style="color: #06c; font-weight: bold;">where</span>
  anyChar :: Rat d <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Char"><span style="background-color: #efefbf; font-weight: bold;">Char</span></a>
&nbsp;
whiteSpace :: Stream d =&gt; Rat d <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
whiteSpace = <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> &lt; $ many <span style="color: green;">&#40;</span>satisfy isSpace<span style="color: green;">&#41;</span>
phrase :: Stream d =&gt; Rat d a -&gt; Rat d a
phrase m = whiteSpace *&gt; m &lt; * eof
&nbsp;
notFollowedBy :: Rat d a -&gt; Rat d <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
notFollowedBy <span style="color: green;">&#40;</span>Rat m<span style="color: green;">&#41;</span> = Rat $ \d -&gt; <span style="color: #06c; font-weight: bold;">case</span> m d <span style="color: #06c; font-weight: bold;">of</span>
  Fail<span style="color: green;">&#123;</span><span style="color: green;">&#125;</span> -&gt; Pure <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
  _      -&gt; Fail <span style="color: #3c7331;">&quot;unexpected&quot;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a>
&nbsp;
eof :: Stream d =&gt; Rat d <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
eof = notFollowedBy anyChar
&nbsp;
satisfy :: Stream d =&gt; <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Char"><span style="background-color: #efefbf; font-weight: bold;">Char</span></a> -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> -&gt; Rat d <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Char"><span style="background-color: #efefbf; font-weight: bold;">Char</span></a>
satisfy p = try $ <span style="color: #06c; font-weight: bold;">do</span>
  x &lt; - anyChar
  x &lt;$ guard <span style="color: green;">&#40;</span>p x<span style="color: green;">&#41;</span>
&nbsp;
char :: Stream d =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Char"><span style="background-color: #efefbf; font-weight: bold;">Char</span></a> -&gt; Rat d <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Char"><span style="background-color: #efefbf; font-weight: bold;">Char</span></a>
char c = satisfy <span style="color: green;">&#40;</span>c ==<span style="color: green;">&#41;</span>
&nbsp;
lexeme :: Stream d =&gt; Rat d a -&gt; Rat d a
lexeme m = m &lt; * whiteSpace
&nbsp;
symbol :: Stream d =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Char"><span style="background-color: #efefbf; font-weight: bold;">Char</span></a> -&gt; Rat d <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Char"><span style="background-color: #efefbf; font-weight: bold;">Char</span></a>
symbol c = lexeme <span style="color: green;">&#40;</span>char c<span style="color: green;">&#41;</span>
&nbsp;
digit :: Stream d =&gt; Rat d <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="background-color: #efefbf; font-weight: bold;">Int</span></a>
digit = digitToInt &lt; $&gt; satisfy isDigit
&nbsp;</pre>
<p>And we can of course use a string as our input stream:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Stream <span style="color: green;">&#91;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Char"><span style="background-color: #efefbf; font-weight: bold;">Char</span></a><span style="color: green;">&#93;</span> <span style="color: #06c; font-weight: bold;">where</span>
  anyChar = Rat $ \s -&gt; <span style="color: #06c; font-weight: bold;">case</span> s <span style="color: #06c; font-weight: bold;">of</span>
    <span style="color: green;">&#40;</span>x:xs<span style="color: green;">&#41;</span> -&gt; Commit xs x
    <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span> -&gt; Fail <span style="color: #3c7331;">&quot;EOF&quot;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a>
&nbsp;</pre>
<p>Now that we've built a poor man's Parsec, let's do something more interesting. Instead of just using String as out input stream, let's include slots for use in memoizing the results from our various parsers at each location. To keep things concrete, we'll memoize the ArithPackrat.hs example that Bryan Ford used in his initial packrat presentation enriched with some whitespace handling.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> D = D
  <span style="color: green;">&#123;</span> _add        :: Result D <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="background-color: #efefbf; font-weight: bold;">Int</span></a>
  , _mult       :: Result D <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="background-color: #efefbf; font-weight: bold;">Int</span></a>
  , _primary    :: Result D <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="background-color: #efefbf; font-weight: bold;">Int</span></a>
  , _decimal    :: Result D <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="background-color: #efefbf; font-weight: bold;">Int</span></a>
  , anyCharD    :: Result D <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Char"><span style="background-color: #efefbf; font-weight: bold;">Char</span></a>
  <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>If you look at the type of each of those functions you'll see that <code>_add :: D -> Result D Int</code>, which is exactly our Rat newtype expects as its argument, we we can bundle them directly:</p>
<pre class="haskell">&nbsp;
&nbsp;
add, mult, primary, decimal :: Rat D <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="background-color: #efefbf; font-weight: bold;">Int</span></a>
add     = Rat _add
mult    = Rat _mult
primary = Rat _primary
decimal = Rat _decimal
&nbsp;</pre>
<p>We can similarly juse use the character parse result.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Stream D <span style="color: #06c; font-weight: bold;">where</span>
  anyChar = Rat anyCharD
&nbsp;</pre>
<p>Now we just need to build a D from a String. I'm using view patterns and record wildcards to shrink the amount of repetitive naming.</p>
<pre class="haskell">&nbsp;
parse :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="background-color: #efefbf; font-weight: bold;">String</span></a> -&gt; D
parse s = fix $ \d -&gt; <span style="color: #06c; font-weight: bold;">let</span>
  Rat <span style="color: green;">&#40;</span>dv d -&gt; _add<span style="color: green;">&#41;</span> =
        <span style="color: green;">&#40;</span>+<span style="color: green;">&#41;</span> &lt; $&gt; mult &lt; * symbol '+' &lt;*&gt; add
     &lt; /&gt; mult
  Rat <span style="color: green;">&#40;</span>dv d -&gt; _mult<span style="color: green;">&#41;</span> =
        <span style="color: green;">&#40;</span>*<span style="color: green;">&#41;</span> &lt; $&gt; primary &lt; * symbol '*' &lt;*&gt; mult
    &lt; /&gt; primary
  Rat <span style="color: green;">&#40;</span>dv d -&gt; _primary<span style="color: green;">&#41;</span> =
        symbol '<span style="color: green;">&#40;</span>' *&gt; add &lt; * symbol '<span style="color: green;">&#41;</span>'
    &lt;/&gt; decimal
  Rat <span style="color: green;">&#40;</span>dv d -&gt; _decimal<span style="color: green;">&#41;</span> =
     <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:foldl"><span style="font-weight: bold;">foldl</span></a>' <span style="color: green;">&#40;</span>\b a -&gt; b * <span style="color: red;">10</span> + a<span style="color: green;">&#41;</span> <span style="color: red;">0</span> &lt; $&gt; lexeme <span style="color: green;">&#40;</span>some digit<span style="color: green;">&#41;</span>
  anyCharD = <span style="color: #06c; font-weight: bold;">case</span> s <span style="color: #06c; font-weight: bold;">of</span>
    <span style="color: green;">&#40;</span>x:xs<span style="color: green;">&#41;</span> -&gt; Commit <span style="color: green;">&#40;</span>parse xs<span style="color: green;">&#41;</span> x
    <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span>     -&gt; Fail <span style="color: #3c7331;">&quot;EOF&quot;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a>
  <span style="color: #06c; font-weight: bold;">in</span> D <span style="color: green;">&#123;</span> .. <span style="color: green;">&#125;</span>
&nbsp;
dv :: d -&gt; <span style="color: green;">&#40;</span>d -&gt; b<span style="color: green;">&#41;</span> -&gt; b
dv d f = f d
&nbsp;</pre>
<p>Note that we didn't really bother factoring the grammar, since packrat will take care of memoizing the redundant calls!</p>
<p>And with that, we can define an evaluator.</p>
<pre class="haskell">&nbsp;
eval :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="background-color: #efefbf; font-weight: bold;">String</span></a> -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="background-color: #efefbf; font-weight: bold;">Int</span></a>
eval s = <span style="color: #06c; font-weight: bold;">case</span> runRat <span style="color: green;">&#40;</span>whiteSpace *&gt; add &lt; * eof<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>parse s<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">of</span>
  Pure a -&gt; a
  Commit _ a -&gt; a
  Fail s _ -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:error"><span style="font-weight: bold;">error</span></a> s
&nbsp;</pre>
<p>Note that because the input stream D contains the result directly and parse is the only thing that ever generates a D, and it does so when we start up, it should be obvious that the parse results for each location can't depend on any additional information smuggled in via our monad.</p>
<p>Next time, we'll add a packratted Stream type directly to Parsec, which will necessitate some delicate handling of user state.</p>
<p>The small parser implemented here can be <a href="https://github.com/ekmett/trifecta/blob/master/wip/Rat.hs">found on my github account</a>, where it hasn't been adulterated with unnecessary spaces by my blog software.</p>
<p>P.S. To explain the quote, had I thought of it earlier, I could have named my parsing combinator library "Kessel Run" as by the time I'm done with it "it will contain at least 12 parsecs" between its different parser implementations.</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2011/a-parsec-full-of-rats/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Free Modules and Functional Linear Functionals</title>
		<link>http://comonad.com/reader/2011/free-modules-and-functional-linear-functionals/</link>
		<comments>http://comonad.com/reader/2011/free-modules-and-functional-linear-functionals/#comments</comments>
		<pubDate>Mon, 11 Jul 2011 20:58:04 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Linear Algebra]]></category>
		<category><![CDATA[Monads]]></category>
		<category><![CDATA[Monoids]]></category>
		<category><![CDATA[Type Hackery]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=356</guid>
		<description><![CDATA[Today I hope to start a new series of posts exploring constructive abstract algebra in Haskell.  
In particular, I want to talk about a novel encoding of linear functionals, polynomials and linear maps in Haskell, but first we're going to have to build up some common terminology.
Having obtained the blessing of Wolfgang Jeltsch, I [...]]]></description>
			<content:encoded><![CDATA[<p>Today I hope to start a new series of posts exploring constructive abstract algebra in Haskell.  </p>
<p>In particular, I want to talk about a novel encoding of linear functionals, polynomials and linear maps in Haskell, but first we're going to have to build up some common terminology.</p>
<p>Having obtained the blessing of Wolfgang Jeltsch, I replaced the <a href="http://hackage.haskell.org/package/algebra">algebra</a> package on hackage with something... bigger, although still very much a work in progress.</p>
<p><span id="more-356"></span></p>
<p><strong>(Infinite) Modules over Semirings</strong></p>
<p>Recall that a vector space <strong>V</strong> over a field <strong>F</strong> is given by an additive Abelian group on <strong>V</strong>, and a scalar multiplication operator<br />
   <code>(.*) :: F -> V -> V</code> subject to distributivity laws</p>
<pre class="haskell">&nbsp;
s .* <span style="color: green;">&#40;</span>u + v<span style="color: green;">&#41;</span> = s .* u + s .* v
<span style="color: green;">&#40;</span>s + t<span style="color: green;">&#41;</span> .* v = s .* v + t .* v
&nbsp;</pre>
<p>and associativity laws</p>
<pre class="haskell">&nbsp;
   <span style="color: green;">&#40;</span>s * t<span style="color: green;">&#41;</span> .* v = s .* <span style="color: green;">&#40;</span>t .* v<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>and respect of the unit of the field.</p>
<pre class="haskell">&nbsp;
   <span style="color: red;">1</span> .* v = v
&nbsp;</pre>
<p>Since multiplication on a field is commutative, we can also add</p>
<pre class="haskell">&nbsp;
  <span style="color: green;">&#40;</span>*.<span style="color: green;">&#41;</span> :: V -&gt; F -&gt; V
  v *. f = f .* v
&nbsp;</pre>
<p>with analogous rules.</p>
<p>But when F is only a <a href="http://en.wikipedia.org/wiki/Ring_(mathematics)">Ring</a>, we call the analogous structure a module, and in a ring, we can't rely on the commutativity of multiplication, so we may have to deal left-modules and right-modules, where only one of those products is available.</p>
<p>We can weaken the structure still further. If we lose the negation in our Ring we and go to a <a href="http://en.wikipedia.org/wiki/Semiring">Rig</a> (often called a Semiring), now our module is an additive moniod.</p>
<p>If we get rid of the additive and multiplicative unit on our Rig we get down to what some authors call a Ringoid, but which we'll call a <a href="http://hackage.haskell.org/packages/archive/algebra/0.3.0/doc/html/Numeric-Semiring-Class.html">Semiring</a> here, because it makes the connection between semiring and semigroup clearer, and the <em>-oid</em> suffix is dangerously overloaded due to category theory.</p>
<p>First we'll define additive semigroups, because I'm going to need both additive and multiplicative monoids over the same types, and Data.Monoid has simultaneously too much and too little structure.</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- (a + b) + c = a + (b + c)</span>
<span style="color: #06c; font-weight: bold;">class</span> Additive m <span style="color: #06c; font-weight: bold;">where</span>
  <span style="color: green;">&#40;</span>+<span style="color: green;">&#41;</span> :: m -&gt; m -&gt; m
  replicate1p :: Whole n =&gt; n -&gt; m -&gt; m <span style="color: #5d478b; font-style: italic;">-- (ignore this for now)</span>
  <span style="color: #5d478b; font-style: italic;">-- ...</span>
&nbsp;</pre>
<p>their Abelian cousins</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- a + b = b + a</span>
<span style="color: #06c; font-weight: bold;">class</span> Additive m =&gt; Abelian m
&nbsp;</pre>
<p>and Multiplicative semigroups</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- (a * b) * c = a * (b * c)</span>
<span style="color: #06c; font-weight: bold;">class</span> Multiplicative m <span style="color: #06c; font-weight: bold;">where</span>
  <span style="color: green;">&#40;</span>*<span style="color: green;">&#41;</span> :: m -&gt; m -&gt; m
  pow1p :: Whole n =&gt; m -&gt; n -&gt; m
  <span style="color: #5d478b; font-style: italic;">-- ...</span>
&nbsp;</pre>
<p>Then we can define a semirings</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- a*(b + c) = a*b + a*c</span>
<span style="color: #5d478b; font-style: italic;">-- (a + b)*c = a*c + b*c</span>
<span style="color: #06c; font-weight: bold;">class</span> <span style="color: green;">&#40;</span>Additive m, Abelian m, Multiplicative m<span style="color: green;">&#41;</span> =&gt; Semiring
&nbsp;</pre>
<p>With that we can define modules over a semiring:</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- r .* (x + y) = r .* x + r .* y</span>
<span style="color: #5d478b; font-style: italic;">-- (r + s) .* x = r .* x + s .* x</span>
<span style="color: #5d478b; font-style: italic;">-- (r * s) .* x = r .* (s .* x)</span>
<span style="color: #06c; font-weight: bold;">class</span> <span style="color: green;">&#40;</span>Semiring r, Additive m<span style="color: green;">&#41;</span> =&gt; LeftModule r m
   <span style="color: green;">&#40;</span>.*<span style="color: green;">&#41;</span> :: r -&gt; m -&gt; m
&nbsp;</pre>
<p>and analogously:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> <span style="color: green;">&#40;</span>Semiring r, Additive m<span style="color: green;">&#41;</span> =&gt; RightModule r m
   <span style="color: green;">&#40;</span>*.<span style="color: green;">&#41;</span> :: m -&gt; r -&gt; m
&nbsp;</pre>
<p>For instance every additive semigroup forms a semiring module over the positive natural numbers (1,2..) using replicate1p.</p>
<p>If we know that our addition forms a monoid, then we can form a module over the naturals as well</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- | zero + a = a = a + zero</span>
<span style="color: #06c; font-weight: bold;">class</span>
    <span style="color: green;">&#40;</span>LeftModule Natural m,
    RightModule Natural m
    <span style="color: green;">&#41;</span> =&gt; AdditiveMonoid m <span style="color: #06c; font-weight: bold;">where</span>
   zero :: m
   replicate :: Whole n =&gt; n -&gt; m -&gt; m
&nbsp;</pre>
<p>and if our addition forms a group, then we can form a module over the integers</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- | a + negate a = zero = negate a + a</span>
<span style="color: #06c; font-weight: bold;">class</span>
    <span style="color: green;">&#40;</span>LeftModule <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Integer"><span style="background-color: #efefbf; font-weight: bold;">Integer</span></a> m
    , RightModule <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Integer"><span style="background-color: #efefbf; font-weight: bold;">Integer</span></a> m
    <span style="color: green;">&#41;</span> =&gt; AdditiveGroup m <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:negate"><span style="font-weight: bold;">negate</span></a> :: m -&gt; m
  times :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Integral"><span style="background-color: #efefbf; font-weight: bold;">Integral</span></a> n =&gt; n -&gt; m -&gt; m
  <span style="color: #5d478b; font-style: italic;">-- ...</span>
&nbsp;</pre>
<p><strong>Free Modules over Semirings</strong></p>
<p>A free module on a set E, is a module where the basis vectors are elements of E. Basically it is |E| copies of some (semi)ring.</p>
<p>In Haskell we can represent the free module of a ring directly by defining the action of the (semi)group pointwise.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Additive m =&gt; Additive <span style="color: green;">&#40;</span>e -&gt; m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   f + g = \x -&gt; f x + g x
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Abelian m =&gt; Abelian <span style="color: green;">&#40;</span>e -&gt; m<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> AdditiveMonoid m =&gt; AdditiveMonoid <span style="color: green;">&#40;</span>e -&gt; m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   zero = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a> zero
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> AdditiveGroup m =&gt; AdditveGroup <span style="color: green;">&#40;</span>e -&gt; m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   f - g = \x -&gt; f x - g x
&nbsp;</pre>
<p>We could define the following</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Semiring r =&gt; LeftModule r <span style="color: green;">&#40;</span>e -&gt; m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   r .* f = \x -&gt; r * f x
&nbsp;</pre>
<p>but then we'd have trouble dealing with the Natural and Integer constraints above, so instead we lift modules</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> LeftModule r m =&gt; LeftModule r <span style="color: green;">&#40;</span>e -&gt; m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   <span style="color: green;">&#40;</span>.*<span style="color: green;">&#41;</span> m f e = m .* f e
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> RightModule r m =&gt; RightModule r <span style="color: green;">&#40;</span>e -&gt; m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   <span style="color: green;">&#40;</span>*.<span style="color: green;">&#41;</span> f m e = f e *. m
&nbsp;</pre>
<p>We <strong>could</strong> go one step further and define multiplication pointwise, but while the direct product of |e| copies of a ring _does_ define a ring, and this ring is the one provided by the Conal Elliot's <a href="http://code.haskell.org/vector-space/"><code>vector-space</code></a> package, it isn't the most general ring we could construct. But we'll need to take a detour first.</p>
<p><strong>Linear Functionals</strong></p>
<p>A Linear functional f on a module M is a linear function from a M to its scalars R.</p>
<p>That is to say that, f : M -> R such that</p>
<pre class="haskell">&nbsp;
f <span style="color: green;">&#40;</span>a .* x + y<span style="color: green;">&#41;</span> = a * f x + f y
&nbsp;</pre>
<p>Consequently linear functionals also form a module over R. We call this module the dual module M*.</p>
<p>Dan Piponi has blogged about these dual vectors (or covectors) in the context of trace diagrams.</p>
<p>If we limit our discussion to free modules, then M = E -> R, so a linear functional on M looks like <code>(E -> R) -> R</code><br />
<em>subject to additional linearity constraints</em> on the result arrow. </p>
<p>The main thing we're not allowed to do in our function is apply our function from E -> R to two different E's and then multiply the results together. Our pointwise definitions above satisfy those linearity constraints, but for example:</p>
<pre class="haskell">&nbsp;
bad f = f <span style="color: red;">0</span> * f <span style="color: red;">0</span>
&nbsp;</pre>
<p>does not.</p>
<p>We <em>could</em> capture this invariant in the type by saying that instead we want</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> LinearM r e =
  LinearM <span style="color: green;">&#123;</span>
    runLinearM :: <span style="color: #06c; font-weight: bold;">forall</span> r. LeftModule r m =&gt; <span style="color: green;">&#40;</span>e -&gt; m<span style="color: green;">&#41;</span> -&gt; m
  <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>we'd have to make a new such type every time we subclassed Semiring. I'll leave further exploration of this more exotic type to another time. (Using some technically illegal module instances we can recover more structure that you'd expect.)</p>
<p>Now we can package up the type of covectors/linear functionals:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">infixr</span> <span style="color: red;">0</span> $*
<span style="color: #06c; font-weight: bold;">newtype</span> Linear r a = Linear <span style="color: green;">&#123;</span> <span style="color: green;">&#40;</span>$*<span style="color: green;">&#41;</span> :: <span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span> -&gt; r <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>The sufficiently observant may have already noticed that this type is the same as the Cont monad (subject to the linearity restriction on the result arrow).</p>
<p>In fact the <code>Functor</code>, <code>Monad</code>, <code>Applicative</code> instances for <code>Cont</code> all carry over, and <strong>preserve linearity</strong>. </p>
<p>(We lose <code>callCC</code>, but that is at least partially due to the fact that <code>callCC</code> has a less than ideal type signature.)</p>
<p>In addition we get a number of additional instances for <code>Alternative</code>, <code>MonadPlus</code>, by exploiting the knowledge that r is ring-like:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> AdditiveMonoid r =&gt; Alternative <span style="color: green;">&#40;</span>Linear r a<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  Linear f &lt; |&gt; Linear g = Linear <span style="color: green;">&#40;</span>f + g<span style="color: green;">&#41;</span>
  empty = Linear zero
&nbsp;</pre>
<p>Note that the <code>(+)</code> and <code>zero</code> there are the ones defined on functions from our earlier free module construction!</p>
<p><strong>Linear Maps</strong></p>
<p>Since <code>Linear r</code> is a monad, <code>Kleisli (Linear r)</code> forms an <code>Arrow</code>:</p>
<pre class="haskell">&nbsp;
b -&gt; <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span> ~&gt; r<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>where the ~> denotes the arrow that is constrained to be linear.</p>
<p>If we swap the order of the arguments so that</p>
<pre class="haskell">&nbsp;
<span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span> ~&gt; <span style="color: green;">&#40;</span>b -&gt; r<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>this arrow has a very nice meaning! (See <a href="http://hackage.haskell.org/packages/archive/algebra/0.4.0/doc/html/Numeric-Map-Linear.html">Numeric.Map.Linear</a>)</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">infixr</span> <span style="color: red;">0</span> $#
<span style="color: #06c; font-weight: bold;">newtype</span> Map r b a = Map <span style="color: green;">&#123;</span> <span style="color: green;">&#40;</span>$#<span style="color: green;">&#41;</span> :: <span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>b -&gt; r<span style="color: green;">&#41;</span> <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p><code>Map r b a</code> represents the type of <a href="http://en.wikipedia.org/wiki/Linear_map">linear maps</a> from <code>a -> b</code>. Unfortunately due to contravariance the arguments wind up in the "wrong" order.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Category <span style="color: green;">&#40;</span>Map r<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  Map f . Map g = Map <span style="color: green;">&#40;</span>g . f<span style="color: green;">&#41;</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a> = Map <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a>
&nbsp;</pre>
<p>So we can see that a linear map from a module A with basis <code>a</code> to a vector space with basis <code>b</code> effectively consists of |b| linear functionals on A.</p>
<p><code>Map r b a</code> provides a lot of structure. It is a valid instance of <a href="https://github.com/ekmett/algebra/blob/master/Numeric/Map/Linear.hs">an insanely large number of classes</a>.</p>
<p><strong>Vectors and Covectors</strong></p>
<p>In physics, we sometimes call linear functionals <a href="http://www.euclideanspace.com/maths/algebra/vectors/related/covector/index.htm">covectors</a> or covariant vectors, and if we're feeling particularly loquacious, we'll refer to vectors as contravariant vectors.</p>
<p>This has to do with the fact that when you change basis, you change map the change over covariant vectors covariantly, and map the change over vectors contravariantly. (This distinction is beautifully captured by <a href="http://en.wikipedia.org/wiki/Einstein_notation">Einstein's summation notation</a>.)</p>
<p>We also have a notion of <a href="http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)">covariance and contravariance in computer science</a>! </p>
<p>Functions vary covariantly in their result, and contravariant in their argument. <code>E -> R</code> is contravariant in E. But we chose this representation for our free modules, so the vectors in our free vector space (or module) are contravariant in E.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> Contravariant f <span style="color: #06c; font-weight: bold;">where</span>
  contramap :: <span style="color: green;">&#40;</span>a -&gt; b<span style="color: green;">&#41;</span> -&gt; f a -&gt; f b
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- | Dual function arrows.</span>
<span style="color: #06c; font-weight: bold;">newtype</span> Op a b = Op <span style="color: green;">&#123;</span> getOp :: b -&gt; a <span style="color: green;">&#125;</span> 
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Contravariant <span style="color: green;">&#40;</span>Op a<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  contramap f g = Op <span style="color: green;">&#40;</span>getOp g . f<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>On the other hand <code>(E -> R) ~> R</code> varies covariantly with the change of <code>E</code>.</p>
<p>as witnessed by the fact that it is a <code>Functor</code>.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>Linear r<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f m = Linear $ \k -&gt; m $* k . f
&nbsp;</pre>
<p>We have lots of classes for manipulating covariant structures, and most of them apply to both (Linear r) and (Map r b).</p>
<p><strong>Other Representations and Design Trade-offs</strong></p>
<p>One common representation of vectors in a free vector space is as some kind of normalized list of scalars and basis vectors. In particular, David Amos's wonderful <a href="http://www.polyomino.f2s.com/david/haskell/main.html">HaskellForMaths</a> uses</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Vect r a = Vect <span style="color: green;">&#123;</span> runVect :: <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span>r,a<span style="color: green;">&#41;</span><span style="color: green;">&#93;</span> <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>for free vector spaces, only considering them up to linearity, paying for normalization as it goes.</p>
<p>Given the insight above we can see that Vect isn't a representation of vectors in the free vector space, but instead represents the covectors of that space, quite simply because Vect r a varies covariantly with change of basis!</p>
<p>Now the price of using the <code>Monad</code> on <code>Vect r</code> is that the monad denormalizes the representation. In particular, you can have multiple copies of the same basis vector., so any function that uses <code>Vect r a</code> has to merge them together.</p>
<p>On the other hand with the directly encoded linear functionals we've described here, we've placed no obligations on the consumer of a linear functional. They can feed the directly encoded linear functional <strong>any vector</strong> they want! </p>
<p>In fact, it'll even be quite a bit more efficient to compute, </p>
<p>To see this, just consider:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> MultiplicativeMonoid r =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> <span style="color: green;">&#40;</span>Vect r<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> a = Vect <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="color: red;">1</span>,a<span style="color: green;">&#41;</span><span style="color: green;">&#93;</span>
   Vect <span style="color: #06c; font-weight: bold;">as</span> &gt;&gt;= f = Vect
       <span style="color: green;">&#91;</span> <span style="color: green;">&#40;</span>p*q, b<span style="color: green;">&#41;</span> | <span style="color: green;">&#40;</span>p,a<span style="color: green;">&#41;</span> &lt; - <span style="color: #06c; font-weight: bold;">as</span>, <span style="color: green;">&#40;</span>q,b<span style="color: green;">&#41;</span> &lt;- runVect <span style="color: green;">&#40;</span>f b<span style="color: green;">&#41;</span> <span style="color: green;">&#93;</span>
&nbsp;</pre>
<p>Every >>= must pay for multiplication. Every return will multiply the element by one. On the other hand, the price of return and bind in Linear r is function application.</p>
</pre>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> <span style="color: green;">&#40;</span>Linear r<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> a = Linear $ \k -&gt; k a
  m &gt;&gt;= f = Linear $ \k -&gt; m $* \a -&gt; f a $* k
&nbsp;</pre>
<p><strong>A Digression on Free Linear Functionals</strong></p>
<p>To wax categorical for a moment, we can construct a forgetful functor <code>U : Vect_F -> Set</code> that takes a vector space over F to just its set of covectors.</p>
<pre lang="haskell>
U (V,F,+,.*) = V ~> F
</pre>
<p>Then we can construct <code>F : Set -> Vect_F</code> which takes a set E and gives the vector space</p>
<pre class="haskell">&nbsp;
F E = <span style="color: green;">&#40;</span>E -&gt; F, F,\f g x -&gt; f x + g x ,\r f x -&gt; r * f x<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>using the pointwise constructions we built earlier.</p>
<p>Then in a classical setting, you can show that F is left adjoint to U.</p>
<p>In particular the witnesses of this adjunction provide the linear map from (E -> F) to V and the function E -> (V ~> F) giving a linear functional on V for each element of E.</p>
<p>In a classical setting you can go a lot farther, and show that all vector spaces (but not all modules) are free.</p>
<p>But in a constructive setting, such as Haskell, we need a fair bit to go back and forth, in particular we wind up need E to be finitely enumerable to go one way, and for it to have decidable equality to go in the other. The latter is fairly easy to see, because even going from <code>E -> (E -> F)</code> requires that we can define and partially apply something like <a href="http://en.wikipedia.org/wiki/Kronecker_delta">Kronecker's delta</a>:</p>
<pre class="haskell">&nbsp;
delta :: <span style="color: green;">&#40;</span>Rig r, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Eq"><span style="background-color: #efefbf; font-weight: bold;">Eq</span></a> a<span style="color: green;">&#41;</span> =&gt; e -&gt; e -&gt; r
delta i j | i == j = one
             | <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:otherwise"><span style="font-weight: bold;">otherwise</span></a> = zero
&nbsp;</pre>
<p><strong>The Price of Power</strong></p>
<p>The price we pay is that, given a <code>Rig</code>, we can go from <code>Vect r a</code> to <code>Linear r a</code> but going back requires <code>a</code> to be be finitely enumerable (or for our functional to satisfy other exotic side-conditions).  </p>
<pre class="haskell">&nbsp;
vectMap :: Rig r =&gt; Vect r a -&gt; Linear r a
vectMap <span style="color: green;">&#40;</span>Vect <span style="color: #06c; font-weight: bold;">as</span><span style="color: green;">&#41;</span> = Map $ \k -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:sum"><span style="font-weight: bold;">sum</span></a> <span style="color: green;">&#91;</span> r * k a | <span style="color: green;">&#40;</span>r, a<span style="color: green;">&#41;</span> &lt; - <span style="color: #06c; font-weight: bold;">as</span> <span style="color: green;">&#93;</span>
&nbsp;</pre>
<p>You can still probe <code>Linear r a</code> for individual coefficients, or pass it a vector for polynomial evaluation very easily, but for instance determining a degree of a polynomial efficiently requires attaching more structure to your semiring, because the only value you can get out of <code>Linear r a</code> is an <code>r</code>.</p>
<p><strong>Optimizing Linear Functionals</strong></p>
<p>In both the <code>Vect r</code> and <code>Linear r</code> cases, excessive use of <code>(>>=)</code> without somehow normalizing or tabulating your data will cause a <strong>lot</strong> of repeated work. </p>
<p>This is perhaps easiest to see from the fact that <code>Vect r</code> never used the addition of <code>r</code>, so it distributed everything into a kind of disjunctive normal form. <code>Linear r</code> does the same thing.</p>
<p>If you look at the Kleisli arrows of <code>Vect r</code> or <code>Linear r</code> as linear mappings, then you can see that Kleisli composition is going to explode the number of terms. </p>
<p>So how can we collapse back down?</p>
<p>In the <code>Kleisli (Vect r)</code> case we usually build up a map as we walk through the list then spit the list back out in order having added up like terms.</p>
<p>In the <code>Map r</code> case, we can do better. My <a href="http://hackage.haskell.org/package/representable-tries"><code>representable-tries</code></a> package provides a readily instantiable <code>HasTrie</code> class, and the method:</p>
</pre>
<pre class="haskell">&nbsp;
memo :: HasTrie a =&gt; <span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span> -&gt; a -&gt; r
&nbsp;</pre>
<p>which is responsible for providing a memoized version of the function from <code>a -> r</code> in a purely functional way. This is obviously a linear map!</p>
<pre class="haskell">&nbsp;
memoMap :: HasTrie a =&gt; Map r a a
memoMap = Map memo
&nbsp;</pre>
<p>We can also flip memo around and memoize linear functionals.</p>
<pre class="haskell">&nbsp;
memoLinear :: HasTrie a =&gt; a -&gt; Linear r a
memoLinear = Linear . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:flip"><span style="font-weight: bold;">flip</span></a> memo
&nbsp;</pre>
<p>Next time, (co)associative (co)algebras and the myriad means of multiplying (co)vectors!</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2011/free-modules-and-functional-linear-functionals/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Free Monads for Less (Part 3 of 3): Yielding IO</title>
		<link>http://comonad.com/reader/2011/free-monads-for-less-3/</link>
		<comments>http://comonad.com/reader/2011/free-monads-for-less-3/#comments</comments>
		<pubDate>Fri, 24 Jun 2011 06:41:06 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Comonads]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Kan Extensions]]></category>
		<category><![CDATA[Monads]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=251</guid>
		<description><![CDATA[<a href="http://comonad.com/reader/2011/free-monads-for-less-2/">Last time</a>, I said that I was going to put our cheap new free monad to work, so let's give it a shot. ]]></description>
			<content:encoded><![CDATA[<p><a href="http://comonad.com/reader/2011/free-monads-for-less-2/">Last time</a>, I said that I was going to put our cheap new free monad to work, so let's give it a shot. </p>
<p><span id="more-251"></span></p>
<p><strong>Yield for Less</strong></p>
<p>Last month at <a href="http://www.pps.jussieu.fr/~saurin/tpdc2011/">TPDC 2011</a>, Roshan James and Amr Sabry presented <a href="http://parametricity.net/dropbox/yield.subc.pdf">Yield: Mainstream Delimited Continuations</a>.</p>
<p>Without calling it such they worked with the free monad of the indexed store comonad. Ignoring the comonad, and just looking at the functor we can see that</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Store i o r = Store <span style="color: green;">&#40;</span>i -&gt; r<span style="color: green;">&#41;</span> o
    <span style="color: #06c; font-weight: bold;">deriving</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>admits the operation</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> y =&gt; Yieldable y i o | y -&gt; i o <span style="color: #06c; font-weight: bold;">where</span>
   yield :: o -&gt; y i
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Yieldable <span style="color: green;">&#40;</span>Store i o<span style="color: green;">&#41;</span> i o <span style="color: #06c; font-weight: bold;">where</span>
   yield = Store <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a>
&nbsp;</pre>
<p>The free monad of <code>Store i o</code> is a nice model for asymmetric coroutines.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Yield i o = Free <span style="color: green;">&#40;</span>Store i o<span style="color: green;">&#41;</span>
&nbsp;
liftFree :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; f a -&gt; Free f a
liftFree = Free . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> Pure
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Yieldable y i o =&gt; Yieldable <span style="color: green;">&#40;</span>Free y<span style="color: green;">&#41;</span> i o <span style="color: #06c; font-weight: bold;">where</span>
   yield = liftFree . yield
&nbsp;</pre>
<p>With its <code>Monad</code>, you can write computations like:</p>
<pre class="haskell">&nbsp;
foo :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="background-color: #efefbf; font-weight: bold;">Num</span></a> o =&gt; Yield <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> o <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
foo = <span style="color: #06c; font-weight: bold;">do</span>
   yield <span style="color: red;">1</span>
   yield <span style="color: red;">2</span>
   yield <span style="color: red;">3</span>
&nbsp;</pre>
<p>or to streamline one of James and Sabry's examples</p>
<pre class="haskell">&nbsp;
walk :: Traversable f =&gt; f o -&gt; Yield i o <span style="color: green;">&#40;</span>f i<span style="color: green;">&#41;</span>
walk = traverse yield
&nbsp;</pre>
<p>is an asymmetric coroutine that yields each of the elements in a traversable container in turn, replacing them with the responses from whatever is driving the coroutine.</p>
<p>James and Sabry called this the naive frame grabbing implementation. It is inefficient for the same reasons that we discussed before about retraversing the common trunk in free monads in general. Note that the unchanging trunk here isn't the data structure that we're traversing, but instead the chain of <code>Store i o</code> actions we took to get to the current instruction.</p>
<p>James and Sabry then proceeded to optimize it by hitting it with <a href="http://hackage.haskell.org/packages/archive/kan-extensions/0.5.0/doc/html/Control-Monad-Codensity.html">Codensity</a>.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Iterator i o = Codensity <span style="color: green;">&#40;</span>Yield i o<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> y, Yieldable y i o<span style="color: green;">&#41;</span> =&gt; Yieldable <span style="color: green;">&#40;</span>Codensity y<span style="color: green;">&#41;</span> i o <span style="color: #06c; font-weight: bold;">where</span>
   yield = liftCodensity . yield
&nbsp;</pre>
<p>But we've now seen that we can get away with something smaller and get the same benefits.</p>
<pre class="haskell">&nbsp;
liftF :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; f a -&gt; F f a
liftF f = F <span style="color: green;">&#40;</span>\kp kf -&gt; kf <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> kp f<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Yieldable y i o =&gt; Yieldable <span style="color: green;">&#40;</span>F y<span style="color: green;">&#41;</span> i o <span style="color: #06c; font-weight: bold;">where</span>
   yield = liftF . yield
&nbsp;</pre>
<p>Flattened, and with the store untupled the new optimized representation looks like:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Iterator i o a = Iterator
  <span style="color: green;">&#123;</span> runIterator ::
    <span style="color: #06c; font-weight: bold;">forall</span> r. <span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>o -&gt; <span style="color: green;">&#40;</span>i -&gt; r<span style="color: green;">&#41;</span> -&gt; r<span style="color: green;">&#41;</span> -&gt; r<span style="color: green;">&#41;</span>
  <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>and provides the same performance improvements for asymmetric coroutines as the <code>Codensity</code> version, used by James and Sabry, which would flatten to the much larger and less satisfying:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> RSIterator i o a = RSIterator
    <span style="color: green;">&#123;</span> runRSIterator :: <span style="color: #06c; font-weight: bold;">forall</span> r.
          <span style="color: green;">&#40;</span>a -&gt; <span style="color: green;">&#40;</span>o -&gt; <span style="color: green;">&#40;</span>i -&gt; r<span style="color: green;">&#41;</span> -&gt; r<span style="color: green;">&#41;</span> -&gt; r<span style="color: green;">&#41;</span>
             -&gt; <span style="color: green;">&#40;</span>o -&gt; <span style="color: green;">&#40;</span>i -&gt; r<span style="color: green;">&#41;</span> -&gt; r<span style="color: green;">&#41;</span> -&gt; r
    <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>They proceed to give an encoding of delimited continuations into this type and vice versa, but the rest of their material is of no further use to us here.</p>
<p>As an aside the performance benefits of encoding Oleg's <a href="http://okmij.org/ftp/Streams.html">iteratees</a> in <a href="http://hackage.haskell.org/packages/archive/iteratee/0.8.5.0/doc/html/Data-Iteratee-Base.html">continuation passing style</a> arise for much the same reason. The resuting encoding is a right Kan extension!</p>
<p><strong>Who Needs the RealWorld?</strong></p>
<p>As <a href="http://twitter.com/#!/runarorama/status/83570792704638976">Runar recently tweeted</a>, we have put this to good use here at <a href="https://www.capitaliq.com/home/what-we-offer/how-you-can-get-it/clarifi.aspx">ClariFI</a>. (<strong>Yes</strong>, we are hiring! If the contents of my blog make sense to you then <a href="mailto:ekmett@gmail.com">email me</a> and let's talk.)</p>
<p>At ClariFI have a strongly typed functional language that bears a strong resemblance to Haskell with <a href="http://www.haskell.org/haskellwiki/Rank-N_types">rank-n types</a> and a number of other interesting type system features that are particularly suited to our problem domain.</p>
<p>However, as with Haskell, we needed a story for how to deal with <code>IO</code>. </p>
<p>Now, <a href="http://www.haskell.org/ghc/">GHC</a> models <a href="http://www.haskell.org/ghc/docs/6.2/html/libraries/base/GHC.IOBase.html">IO</a> with the type</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:IO"><span style="background-color: #efefbf; font-weight: bold;">IO</span></a> a =
   <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:IO"><span style="background-color: #efefbf; font-weight: bold;">IO</span></a> <span style="color: green;">&#40;</span>State# RealWorld -&gt; <span style="color: green;">&#40;</span># a, State# RealWorld #<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>where they model <code>IO</code> by working in a strict state monad, passing around a real world that they promise not to mutate or copy. (In practice, the world is passed around as a 0-byte token.</p>
<p>This is somewhat problematic semantically, for a number of reasons.</p>
<p>First, There is always the risk of copying it or plumbing it through backwards, so we carefully hide the <code>State# RealWorld</code> from the end user. So this model really wants some notion of uniqueness or linear typing to render it perfectly safe. Heck, the entire <a href="http://en.wikipedia.org/wiki/Clean_(programming_language)">Clean</a> language arose from just trying to address this concern.</p>
<p>Second, you don't <strong>really</strong> get to pass the real world around!  We have multiple cores working these days. Stuff is happening in the back end, and as much as you might want it to be, your program isn't responsible for everything that happens in the <code>RealWorld</code>!.</p>
<p>Third, if in some sense all bottoms are the same, then <code>forever (putStrLn "Hello World")</code> and <code>undefined</code> are the same in that sense, despite the slew of side-effects that arise from the first one. Now, in Haskell you are allowed to catch some bottoms in the IO monad, and thereby escape from certain doom, but it is still a reasonable objection.</p>
<p>One alternate model for talking about <code>IO</code> is to view it as a free monad of some set of operations. This approach was taken by Wouter Swierstra's Functional Pearl: <a href="http://www.cs.nott.ac.uk/~wss/Publications/DataTypesALaCarte.pdf">Data Types a la Carte</a>.</p>
<p>You can then supply some sort of external interpreter that pumps that tree structure, performing the individual actions.</p>
<p>This is unsatisfying because of two things:</p>
<p>First, the performance is abysmal using the common ADT encoding of a free monad. Janis Voigtländer of course showed, that this can be rectified by using the <code>Codensity</code> monad.</p>
<p>Second, the set of <code>FFI</code> operations is closed.</p>
<p>What we've done instead is to define our primitive <code>IO</code> actions externally as some <code>FFI</code> type:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> FFI o i <span style="color: #5d478b; font-style: italic;">-- external, side-effecting computation taking o, returning i</span>
&nbsp;</pre>
<p>In practice, these are obtained by reflection by our <code>foreign import</code> statements since we run in the JVM.</p>
<p>Then we looked at the free monad of</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> OI a = <span style="color: #06c; font-weight: bold;">forall</span> o i. OI <span style="color: green;">&#40;</span>FFI o i<span style="color: green;">&#41;</span> o <span style="color: green;">&#40;</span>i -&gt; a<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">deriving</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a>
&nbsp;</pre>
<p>where <code>OI</code> is the indexed store comonad used as the building block above, yielding arguments to <code>FFI</code> of type <em>o</em>, and representing a computation that would resume with a value of type <em>i</em> to obtain a result of type <em>a</em>.<code></p>
<p>In some sense this yields a more useful notion than Richard Kieburtz's novel, but largely unimplementable, </code><code>OI</code> comonad from <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.45.4741&rep=rep1&type=ps">Codata and Comonads in Haskell</a>.</p>
<p>Flattening <code>Free OI</code> would yield the naive</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- data FIO a where</span>
<span style="color: #5d478b; font-style: italic;">--    Return :: a -&gt; FIO a</span>
<span style="color: #5d478b; font-style: italic;">--    FIO :: FFI o i -&gt; o -&gt; (i -&gt; FIO a) -&gt; FIO a</span>
&nbsp;</pre>
<p>which would be interpreted by the runtime system.</p>
<p>But once we've converted to our Church-encoded Free monad and flattened we obtain:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:IO"><span style="background-color: #efefbf; font-weight: bold;">IO</span></a> a = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:IO"><span style="background-color: #efefbf; font-weight: bold;">IO</span></a>
    <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> r. <span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span> -&gt;
                 <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> i o. FFI o i -&gt; o -&gt; <span style="color: green;">&#40;</span>i -&gt; r<span style="color: green;">&#41;</span> -&gt; r<span style="color: green;">&#41;</span> -&gt;
                 r<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>with the <code>Functor</code> and <code>Monad</code> instances defined above.</p>
<p>This then gives us a number of choices on how we implement the runtime system:</p>
<p>We can use the machinery described earlier to convert from <code>IO a</code> to <code>Free OI a</code> or <code>FIO a</code>, and then have the runtime system pattern match on that structure on our main method, taking the <code>FFI</code> actions and their arguments and passing the results in to the language, or we can invert control, and implement things more directly by just defining </p>
<pre class="haskell">&nbsp;
FFI = <span style="color: green;">&#40;</span>-&gt;<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>while letting the <code>FFI</code>'d methods have side-effects, and then defining</p>
<pre class="haskell">&nbsp;
unsafePerformIO :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:IO"><span style="background-color: #efefbf; font-weight: bold;">IO</span></a> a -&gt; a
unsafePerformIO <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:IO"><span style="background-color: #efefbf; font-weight: bold;">IO</span></a> m<span style="color: green;">&#41;</span> = m <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a> <span style="color: green;">&#40;</span>\ oi o ir -&gt; ir <span style="color: green;">&#40;</span>oi o<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>But regardless of how <code>FFI</code> is implemented,  this model provides a clear structural difference between <code>forever (putStrLn "Hello")</code> and <code>undefined</code> and does not require us to believe the pleasant fiction that we can get our hands on the real world and pass it around.</p>
<p>Our actual <code>IO</code> representation is only slightly more complicated than the one presented here in order to deal with the plumbing of an extra continuation to deal with Java exceptions, but the substance of this approach isn't changed by this addition.</p>
<p>[Edit: incorporated a minor typographical fix into Iterator from Max Bolingbroke]<br />
[Edit: fixed Store to be data, an liftM that should have been an fmap and added the missing Functor constraint that was present in my actual implementation but didn't make it to the web, and a couple of typos in the implementation of RSIterator, all noted by Clumsy.]</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2011/free-monads-for-less-3/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Free Monads for Less (Part 2 of 3): Yoneda</title>
		<link>http://comonad.com/reader/2011/free-monads-for-less-2/</link>
		<comments>http://comonad.com/reader/2011/free-monads-for-less-2/#comments</comments>
		<pubDate>Fri, 24 Jun 2011 04:49:46 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Kan Extensions]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Monads]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=243</guid>
		<description><![CDATA[Last time, I started exploring whether or not Codensity was necessary to improve the asymptotic performance of free monads.
This time I'll show that the answer is no; we can get by with something smaller.

The Yoneda Lemma
Another form of right Kan extension arises from the Yoneda lemma.
I covered it briefly in my initial article on Kan [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://comonad.com/reader/2011/free-monads-for-less/">Last time</a>, I started exploring whether or not <a href="http://hackage.haskell.org/packages/archive/kan-extensions/0.5.0/doc/html/Control-Monad-Codensity.html">Codensity</a> was necessary to <a href="http://www.iai.uni-bonn.de/~jv/mpc08.pdf">improve the asymptotic performance of free monads</a>.</p>
<p>This time I'll show that the answer is no; we can get by with something smaller.</p>
<p><span id="more-243"></span></p>
<p><b>The Yoneda Lemma</b></p>
<p>Another form of right Kan extension arises from the <a href="http://en.wikipedia.org/wiki/Yoneda_lemma">Yoneda lemma</a>.</p>
<p>I covered it briefly in <a href="http://comonad.com/reader/2008/kan-extensions/">my initial article on Kan extensions</a>, but the inestimable Dan Piponi wrote a <a href="http://blog.sigfpe.com/2006/11/yoneda-lemma.html">much nicer article</a> on how it implies in Haskell that given a <code>Functor</code> instance on <em>f</em>, this type</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Yoneda f a = Yoneda <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> r. <span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span> -&gt; f r<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>is isomorphic to <code>f a</code>, witnessed by these natural transformations:</p>
<pre class="haskell">&nbsp;
liftYoneda :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; f a -&gt; Yoneda f a
liftYoneda a = Yoneda <span style="color: green;">&#40;</span>\f -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f a<span style="color: green;">&#41;</span>
&nbsp;
lowerYoneda :: Yoneda f a -&gt; f a
lowerYoneda <span style="color: green;">&#40;</span>Yoneda f<span style="color: green;">&#41;</span> = f <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a>
&nbsp;</pre>
<p>That said, <em>you are not limited to applying <code>Yoneda</code> to types that have <code>Functor</code> instances</em>.</p>
<p>This type and these functions are provided by <a href="http://hackage.haskell.org/packages/archive/kan-extensions/0.5.0/doc/html/Data-Functor-Yoneda.html">Data.Functor.Yoneda</a> from the <a href="http://hackage.haskell.org/package/kan-extensions">kan-extensions</a> package.</p>
<p><b>Codensity vs. Yoneda</b></p>
<p>Note, <code>Yoneda f</code> is in some sense smaller than <code>Codensity f</code>, as <code>Codensity f a</code> is somewhat 'bigger' than <code>f a</code>, despite providing an embedding, while <code>Yoneda f a</code> is isomorphic.</p>
<p>For example, <code>Codensity ((->) s) a</code> is isomorphic to <code>State s a</code>, not to <code>s -&gt; a</code> as shown by: </p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> MonadState s <span style="color: green;">&#40;</span>Codensity <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>-&gt;<span style="color: green;">&#41;</span> s<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   get = Codensity <span style="color: green;">&#40;</span>\k s -&gt; k s s<span style="color: green;">&#41;</span>
   put s = Codensity <span style="color: green;">&#40;</span>\k _ -&gt; k <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> s<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Now, <code>Codensity</code> is a particular form of right Kan extension, which always yields a <code>Monad</code>, <b>without needing anything from <em>f</em></b>.</p>
<p>Here we aren't so fortunate, but we do have the fact that <code>Yoneda f</code> is always a <code>Functor</code>, regardless of what <em>f</em> is, as shown by:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>Yoneda f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>Yoneda m<span style="color: green;">&#41;</span> = Yoneda <span style="color: green;">&#40;</span>\k -&gt; m <span style="color: green;">&#40;</span>k . f<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>which was obtained just by cutting and pasting the appropriate definition from <code>Codensity</code> or <code>ContT</code>, and comes about because <code>Yoneda</code> is a right Kan extension, like all of those. </p>
<p>To get a <code>Monad</code> instance for <code>Yoneda f</code> we need to lean on <em>f</em> somehow.</p>
<p>One way is to just borrow a <code>Monad</code> instance from <em>f</em>, since <code>f a</code> is isomorphic to <code>Yoneda f a</code>, if we have a <code>Functor</code> for <em>f</em>, and if we have a <code>Monad</code>, we can definitely have a <code>Functor</code>.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> <span style="color: green;">&#40;</span>Yoneda m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> a = Yoneda <span style="color: green;">&#40;</span>\f -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
  Yoneda m &gt;&gt;= k = Yoneda <span style="color: green;">&#40;</span>\f -&gt; m <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a> &gt;&gt;= \a -&gt; runYoneda <span style="color: green;">&#40;</span>k a<span style="color: green;">&#41;</span> f<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p><strong>Map Fusion and Reassociating Binds</strong></p>
<p>Unlike <code>Codensity</code> the monad instance above isn't very satisfying, because it uses the <code>>>=</code> of the underlying monad, and as a result the <code>>>=</code>s will wind up in the same order they started.</p>
<p>On the other hand, the <code>Functor</code> instance for <code>Yoneda f</code> is still pretty nice because the <code>(a -&gt; r)</code> part of the type acts as an accumulating parameter fusing together uses of <code>fmap</code>.</p>
<p>This is apparent if you expand <code>lowerYoneda . fmap f . fmap g . liftYoneda </code>, whereupon you can see we only call <code>fmap</code> on the underlying <code>Functor</code> once.</p>
<p>Intuitively, you can view <code>Yoneda</code> as a type level construction that ensures that you get <code>fmap</code> fusion, while <code>Codensity</code> is a type level construction that ensures that you right associate binds. It is important to note that <code>Codensity</code> also effectively accumulates <code>fmap</code>s, as it uses the same definition for <code>fmap</code> as <code>Yoneda</code>!</p>
<p>With this in mind, it doesn't usually make much sense to use <code>Codensity (Codensity m)</code> or <code>Yoneda (Yoneda m)</code> because the purpose being served is redundant.</p>
<p>Less obviously, <code>Codensity (Yoneda m)</code> is also redundant, because as noted above, <code>Codensity</code> also does <code>fmap</code> accumulation.</p>
<p><strong>Other Yoneda-transformed Monads</strong></p>
<p>Now, I said one way to define a <code>Monad</code> for <code>Yoneda f</code> was to borrow an underlying <code>Monad</code> instance for <em>f</em>, but this isn't the only way.</p>
<p>Consider <code>Yoneda Endo</code>. Recall that <code>Endo</code> from <a href="http://www.haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/Data-Monoid.html">Data.Monoid</a> is given by</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Endo a = Endo <span style="color: green;">&#123;</span> appEndo :: a -&gt; a <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>Clearly <code>Endo</code> is not a <code>Monad</code>, it can't even be a <code>Functor</code>, because <em>a</em> occurs in both positive and negative position.</p>
<p>Nevertheless <code>Yoneda Endo</code> <strong>can</strong> be made into a monad -- the continuation passing style version of the <code>Maybe</code> monad!</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> YMaybe a = YMaybe <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> r. <span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span> -&gt; r -&gt; r<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>I leave the rather straightforward derivation of this <code>Monad</code> for the reader. A version of it is present in <a href="http://comonad.com/haskell/monad-ran/dist/doc/html/monad-ran/Control-Monad-Ran.html">monad-ran</a>.</p>
<p>This lack of care for capital-F <code>Functor</code>iality also holds for <code>Codensity</code>, <code>Codensity Endo</code> can be used as a two-continuation list monad. It is isomorphic to the non-transformer version of <a href="http://okmij.org/ftp/papers/LogicT.pdf">Oleg et al.'s LogicT</a>, which is available on hackage as <a href="http://hackage.haskell.org/packages/archive/logict/0.4.2/doc/html/Control-Monad-Logic.html">logict</a> from my coworker, Dan Doel.</p>
<p>The <code>Functor</code>, <code>Applicative</code>, <code>Monad</code>, <code>MonadPlus</code> and many other instances for <code>LogicT</code> can be rederived in their full glory from <code>Codensity (GEndo m)</code> automatically, where</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> GEndo m r = GEndo <span style="color: green;">&#40;</span>m r -&gt; m r<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>without any need for conscious thought about how the continuations are plumbed through in the <code>Monad</code>.</p>
<p><strong>Bananas in Space</strong></p>
<p>One last digression,</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Rec f r = <span style="color: green;">&#40;</span>f r -&gt; r<span style="color: green;">&#41;</span> -&gt; r
&nbsp;</pre>
<p>came up once previously on this blog in <a href="http://comonad.com/reader/2008/rotten-bananas/">Rotten Bananas</a>. In that post, I talked about how Fegaras and Sheard used a free monad (somewhat obliquely) in "<a href="http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.36.2763">Revisiting catamorphisms over datatypes with embedded functions</a>" to extend catamorphisms to deal with strong HOAS, and then talked further about how Stephanie Weirich and Geoffrey Washburn <a href="http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.80.2219">used Rec</a> to replace the free monad used by Fegaras and Sheard. That said, they did so in a more restricted context, where any mapping was done by giving us both an embedding and a projection pair.</p>
<p><strong>Going to Church</strong></p>
<p>We can't just use <code>Rec f a</code> instead of <code>Free f a</code> here, because <code>Free f a</code> is a functor, while <code>Rec f a</code> is emphatically not. </p>
<p>However, if we apply <code>Yoneda</code> to <code>Rec f</code>, we obtain a Church-encoded continuation-passing-style version of <code>Free</code>!</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> F f a = F <span style="color: green;">&#123;</span> runF :: <span style="color: #06c; font-weight: bold;">forall</span> r. <span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>f r -&gt; r<span style="color: green;">&#41;</span> -&gt; r <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>Since this is of the form of <code>Yoneda (Rec f)</code>, it is clearly a <code>Functor</code>:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>F f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>F g<span style="color: green;">&#41;</span> = F <span style="color: green;">&#40;</span>\kp -&gt; g <span style="color: green;">&#40;</span>kp . f<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>And nicely, <strong>without knowing anything about <em>f</em></strong>, we also get a <code>Monad</code>!</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> <span style="color: green;">&#40;</span>F f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> a = F <span style="color: green;">&#40;</span>\kp _ -&gt; kp a<span style="color: green;">&#41;</span>
   F m &gt;&gt;= f = F <span style="color: green;">&#40;</span>\kp kf -&gt; m <span style="color: green;">&#40;</span>\a -&gt; runF <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span> kp kf<span style="color: green;">&#41;</span> kf<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>But when we <code>>>=</code> all we do is change the continuation for <code>(a -&gt; r)</code>, leaving the <em>f</em>-algebra, <code>(f r -&gt; r)</code>, untouched.</p>
<p>Now, <code>F</code> is a monad transformer:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> MonadTrans F <span style="color: #06c; font-weight: bold;">where</span>
   lift f = F <span style="color: green;">&#40;</span>\kp kf -&gt; kf <span style="color: green;">&#40;</span>liftM kp f<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>which is unsurprisingly, effectively performing the same operation as lifting did in <code>Free</code>.</p>
<p>Heretofore, we've ignored everything about <em>f</em> entirely. </p>
<p>This has pushed the need for the <code>Functor</code> on <em>f</em> into the wrapping operation:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; MonadFree f <span style="color: green;">&#40;</span>F f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   wrap f = F <span style="color: green;">&#40;</span>\kp kf -&gt; kf <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>\ <span style="color: green;">&#40;</span>F m<span style="color: green;">&#41;</span> -&gt; m kp kf<span style="color: green;">&#41;</span> f<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Now, we can clearly transform from our representation to any other free monad representation:</p>
<pre class="haskell">&nbsp;
fromF :: MonadFree f m =&gt; F f a -&gt; m a
fromF <span style="color: green;">&#40;</span>F m<span style="color: green;">&#41;</span> = m <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> wrap
&nbsp;</pre>
<p>or to it from our original canonical ADT-based free monad representation:</p>
<pre class="haskell">&nbsp;
toF :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; Free f a -&gt; F f a
toF xs = F <span style="color: green;">&#40;</span>\kp kf -&gt; go kp kf xs<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  go kp _  <span style="color: green;">&#40;</span>Pure a<span style="color: green;">&#41;</span> = kp a
  go kp kf <span style="color: green;">&#40;</span>Free fma<span style="color: green;">&#41;</span> = kf <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>go kp kf<span style="color: green;">&#41;</span> fma<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>So, <code>F f a</code> is isomorphic to <code>Free f a</code>.</p>
<p>So, looking at <code>Codensity (F f) a</code> as <code>Codensity (Yoneda (Rec f))</code>, it just seems silly. </p>
<p>As we mentioned before, we should be able to go from <code>Codensity (Yoneda (Rec f)) a</code> to <code>Codensity (Rec f) a</code>, since <code>Yoneda</code> was just fusing uses of <code>fmap</code>, while <code>Codensity</code> was fusing <code>fmap</code> while right-associating <code>(>>=)</code>'s.</p>
<p><strong>Swallowing the Bigger Fish</strong></p>
<p>So, the obvious choice is to try to optimize to <code>Codensity (Rec f) a</code>. If you go through the motions of encoding that you get:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> CF f a = CF <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> r. <span style="color: green;">&#40;</span>a -&gt; <span style="color: green;">&#40;</span>f r -&gt; r<span style="color: green;">&#41;</span> -&gt; r<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>f r -&gt; r<span style="color: green;">&#41;</span> -&gt; r<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>which is in some sense larger than <code>F f a</code>, because the first continuation gets both an <em>a</em> and an <em>f</em>-algebra <code>(f r -&gt; r)</code>.</p>
<p>But tellingly, once you write the code, the first continuation <strong>never uses the extra <em>f</em>-algebra you supplied it!</strong></p>
<p>So <code>Codensity (Yoneda (Rec f)) a</code> gives us nothing of interest that we don't already have in <code>Yoneda (Rec f) a</code>.</p>
<p>Consequently, in this special case rather than letting <code>Codensity (Yoneda x) a</code> swallow the <code>Yoneda</code> to get <code>Codensity x a</code> we can actually let the <code>Yoneda</code> swallow the surrounding <code>Codensity</code> obtaining <code>Yoneda (Rec f) a</code>, the representation we started with.</p>
<p><strong>Scott Free</strong></p>
<p>Finally, you might ask if a Church encoding is as simple as we could go. After all a Scott encoding</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> ScottFree f a = ScottFree
    <span style="color: green;">&#123;</span> runScottFree :: <span style="color: #06c; font-weight: bold;">forall</span> r.
       <span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>f <span style="color: green;">&#40;</span>ScottFree f a<span style="color: green;">&#41;</span> -&gt; r<span style="color: green;">&#41;</span> -&gt; r
    <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>would admit easier pattern matching, and a nice pun, and seems somewhat conceptually simpler, while remaining isomorphic.</p>
<p>But the <code>Monad</code> instance:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> <span style="color: green;">&#40;</span>ScottFree f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> a = ScottFree <span style="color: green;">&#40;</span>\kp _ -&gt; kp a<span style="color: green;">&#41;</span>
   ScottFree m &gt;&gt;= f = ScottFree
       <span style="color: green;">&#40;</span>\kb kf -&gt; m <span style="color: green;">&#40;</span>\a -&gt; runScottFree <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span> kb kf<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>kf . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>&gt;&gt;= f<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>needs to rely on the underlying bind, and you can show that it won't do the right thing with regards to reassociating.</p>
<p>So, alas, we cannot get away with <code>ScottFree</code>.</p>
<p><strong>Nobody Sells for Less</strong></p>
<p>So, now we can rebuild Voigtländer's <code>improve</code> using our Church-encoded / Yoneda-based free monad <code>F</code>, which is precisely isomorphic to <code>Free</code>, by using</p>
<pre class="haskell">&nbsp;
lowerF :: F f a -&gt; Free f a
lowerF <span style="color: green;">&#40;</span>F f<span style="color: green;">&#41;</span> = f Pure Free
&nbsp;</pre>
<p>to obtain</p>
<pre class="haskell">&nbsp;
improve :: <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> a. MonadFree f m =&gt; m a<span style="color: green;">&#41;</span> -&gt; Free f a
improve m = lowerF m
&nbsp;</pre>
<p>And since our Church-encoded free monad is isomorphic to the simple ADT encoding, our new solution is as small as it can get.</p>
<p>Next time, we'll see this construction in action!</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2011/free-monads-for-less-2/feed/</wfw:commentRss>
		<slash:comments>426</slash:comments>
		</item>
		<item>
		<title>Free Monads for Less (Part 1 of 3): Codensity</title>
		<link>http://comonad.com/reader/2011/free-monads-for-less/</link>
		<comments>http://comonad.com/reader/2011/free-monads-for-less/#comments</comments>
		<pubDate>Fri, 24 Jun 2011 03:59:58 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Kan Extensions]]></category>
		<category><![CDATA[Monads]]></category>
		<category><![CDATA[free monads]]></category>
		<category><![CDATA[io]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=218</guid>
		<description><![CDATA[A couple of years back <a href="http://www.iai.uni-bonn.de/~jv/">Janis Voigtländer</a> wrote <a href="http://www.iai.uni-bonn.de/~jv/mpc08.pdf">a nice paper</a> on how one can use the codensity monad to improve the asymptotic complexity of algorithms using the free monads. This has been shown to be a sufficient tool for this task, but is it necessary?]]></description>
			<content:encoded><![CDATA[<p>A couple of years back <a href="http://www.iai.uni-bonn.de/~jv/">Janis Voigtländer</a> wrote <a href="http://www.iai.uni-bonn.de/~jv/mpc08.pdf">a nice paper</a> on how one can use the codensity monad to improve the asymptotic complexity of algorithms using the free monads. He didn't use the name <a href="http://hackage.haskell.org/packages/archive/kan-extensions/0.5.0/doc/html/Control-Monad-Codensity.html">Codensity</a> in the paper, but this is essentially the meaning of his type <code>C</code>. </p>
<p>I just returned from <a href="http://www.cas.mcmaster.ca/~anand/DSL2011.html">running a workshop on domain-specific languages at McMaster University</a> with the more than able assistance of <a href="http://llama.freegeek.org/~wren/thornton_cv.pdf">Wren Ng Thornton</a>. Among the many topics covered, I spent a lot of time talking about how to use free monads to build up term languages for various DSLs with simple evaluators, and then made them efficient by using <code>Codensity</code>.</p>
<p>This has been shown to be a sufficient tool for this task, but is it necessary?</p>
<p><span id="more-218"></span></p>
<p>First, some context:</p>
<p><strong>Monads for Free</strong></p>
<p>Given that <em>f</em> is a <code>Functor</code>, we get that </p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Free f a = Pure a | Free <span style="color: green;">&#40;</span>f <span style="color: green;">&#40;</span>Free f a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>is a <code>Monad</code> for free:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>Free f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>Pure a<span style="color: green;">&#41;</span> = Pure <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span>
   <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>Free <span style="color: #06c; font-weight: bold;">as</span><span style="color: green;">&#41;</span> = Free <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">as</span><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> <span style="color: green;">&#40;</span>Free f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> = Pure
   Pure a &gt;&gt;= f = f a <span style="color: #5d478b; font-style: italic;">-- the first monad law!</span>
   Free <span style="color: #06c; font-weight: bold;">as</span> &gt;&gt;= f = Free <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>&gt;&gt;= f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">as</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>The definition is also free in a particular categorical sense, that if <em>f</em> is a monad, then, and you have a forgetful functor that forgets that it is a monad and just yields the functor, then the the free construction above is left adjoint to it.</p>
<p>This type and much of the code below is actually provided by <a href="http://hackage.haskell.org/packages/archive/comonad-transformers/1.7/doc/html/Control-Monad-Trans-Free.html">Control.Monad.Trans.Free</a> in the <a href="http://hackage.haskell.org/package/comonad-transformers">comonad-transformers</a> package on hackage. </p>
<p>For a while, Free lived in a separate, now defunct, package named <code>free</code> with its dual <a href="http://hackage.haskell.org/packages/archive/comonad-transformers/1.7/doc/html/Control-Comonad-Trans-Cofree.html">Cofree</a>, but it was merged into comonad-transformers due to complications involving <a href="http://hackage.haskell.org/package/comonads-fd">comonads-fd</a>, the comonadic equivalent of the mtl.  Arguably, a better home would be transformers, to keep symmetry.</p>
<p><strong>Free is a Monad Transformer</strong></p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> MonadTrans Free <span style="color: #06c; font-weight: bold;">where</span>
    lift = Free . liftM Pure
&nbsp;</pre>
<p>and there exists a <a href="http://en.wikipedia.org/wiki/Retract_(category_theory)">retraction</a> for lift</p>
<pre class="haskell">&nbsp;
retract :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> f =&gt; Free f a -&gt; f a
retract <span style="color: green;">&#40;</span>Pure a<span style="color: green;">&#41;</span> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> a
retract <span style="color: green;">&#40;</span>Free <span style="color: #06c; font-weight: bold;">as</span><span style="color: green;">&#41;</span> = <span style="color: #06c; font-weight: bold;">as</span> &gt;&gt;= retract
&nbsp;</pre>
<p>such that <code>retract . lift = id</code>. I've <a href="http://stackoverflow.com/questions/6221531/how-to-convert-a-free-monad-into-a-functor/6231795#6231795">spoken about this on Stack Overflow</a>, including the rather trivial proof, previously.</p>
<p>This lets us work in <code>Free m a</code>, then flatten back down to a single layer of <em>m</em>. </p>
<p>This digression will be useful in a subsequent post.</p>
<p><strong>MonadFree</strong></p>
<p>What Janis encapsulated in his paper is the notion that we can abstract out the extra power granted by a free monad to add layers of <em>f</em> to some monad <em>m</em>, and then use a better representation to improve the asymptotic performance of the monad. </p>
<p>The names below have been changed slightly from his presentation.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f<span style="color: green;">&#41;</span> =&gt; MonadFree f m | m -&gt; f <span style="color: #06c; font-weight: bold;">where</span>
    wrap :: f <span style="color: green;">&#40;</span>m a<span style="color: green;">&#41;</span> -&gt; m a
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; MonadFree f <span style="color: green;">&#40;</span>Free f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
    wrap = Free
&nbsp;</pre>
<p>instances can easily be supplied to lift <code>MonadFree</code> over the common monad transformers. For instance:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f, MonadFree f m<span style="color: green;">&#41;</span> =&gt; MonadFree f <span style="color: green;">&#40;</span>ReaderT e m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
    wrap fs = ReaderT $ \e -&gt; wrap $ <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>`runReaderT` e<span style="color: green;">&#41;</span> fs
&nbsp;</pre>
<p>This functionality is provided by <a href="http://hackage.haskell.org/packages/archive/comonads-fd/1.7/doc/html/Control-Monad-Free-Class.html">Control.Monad.Free.Class</a>.</p>
<p>Janis then proceeded to define the aforementioned type <code>C</code>, which is effectively identical to</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Codensity f a = Codensity <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> r. <span style="color: green;">&#40;</span>a -&gt; f r<span style="color: green;">&#41;</span> -&gt; f r<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>This type is supplied by <a href="http://hackage.haskell.org/packages/archive/kan-extensions/0.5.0/doc/html/Control-Monad-Codensity.html">Control.Monad.Codensity</a> from my <a href="http://hackage.haskell.org/package/kan-extensions">kan-extensions</a> package on hackage.</p>
<p>I have spoken about this type (and another that will arise in a subsequent post) on this blog previously, in a series of posts on Kan Extensions.  [ <a href="http://comonad.com/reader/2008/kan-extensions/">1</a>, <a href="http://comonad.com/reader/2008/kan-extensions-ii/">2</a>, <a href="http://comonad.com/reader/2008/kan-extension-iii/">3</a>]</p>
<p><code>Codensity f</code> is a <code>Monad</code>, <strong>regardless</strong> of what <em>f</em> is!</p>
<p>In fact, you can quite literally cut and paste much of the definitions for <code>return</code>, <code>fmap</code>, and <code>(>>=)</code> from the code for the <code>ContT</code> monad transformer! Compare</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>Codensity k<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>Codensity m<span style="color: green;">&#41;</span> = Codensity <span style="color: green;">&#40;</span>\k -&gt; m <span style="color: green;">&#40;</span>k . f<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> <span style="color: green;">&#40;</span>Codensity f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> x = Codensity <span style="color: green;">&#40;</span>\k -&gt; k x<span style="color: green;">&#41;</span>
  m &gt;&gt;= k = Codensity <span style="color: green;">&#40;</span>\c -&gt; runCodensity m <span style="color: green;">&#40;</span>\a -&gt; runCodensity <span style="color: green;">&#40;</span>k a<span style="color: green;">&#41;</span> c<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> MonadTrans Codensity <span style="color: #06c; font-weight: bold;">where</span>
   lift m = Codensity <span style="color: green;">&#40;</span>m &gt;&gt;=<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>from <a href="http://hackage.haskell.org/packages/archive/kan-extensions/0.5.0/doc/html/src/Control-Monad-Codensity.html">Control.Monad.Codensity</a> in <a href="http://hackage.haskell.org/package/kan-extensions">kan-extensions</a> with</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>ContT r m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f m = ContT $ \c -&gt; runContT m <span style="color: green;">&#40;</span>c . f<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> <span style="color: green;">&#40;</span>ContT r m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> a = ContT <span style="color: green;">&#40;</span>$ a<span style="color: green;">&#41;</span>
    m &gt;&gt;= k  = ContT $ \c -&gt; runContT m <span style="color: green;">&#40;</span>\a -&gt; runContT <span style="color: green;">&#40;</span>k a<span style="color: green;">&#41;</span> c<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> MonadTrans <span style="color: green;">&#40;</span>ContT r<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
    lift m = ContT <span style="color: green;">&#40;</span>m &gt;&gt;=<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>from the <a href="http://hackage.haskell.org/packages/archive/transformers/0.2.2.0/doc/html/src/Control-Monad-Trans-Cont.html">Control.Monad.Trans.Cont</a> in <a href="http://hackage.haskell.org/package/transformers-0.2.2.0">transformers</a>.</p>
<p><code>Codensity m a</code> is effectively <code>forall r. ContT r m a</code>. This turns out to be just enough of a restriction to rule out the use of <a href="http://hackage.haskell.org/packages/archive/transformers/0.2.2.0/doc/html/Control-Monad-Trans-Cont.html#v:callCC">callCC</a>, while leaving the very powerful fact that when you lower them back down using</p>
<pre class="haskell">&nbsp;
lowerCodensity :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m =&gt; Codensity m a -&gt; m a
lowerCodensity <span style="color: green;">&#40;</span>Codensity m<span style="color: green;">&#41;</span> = m <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a>
&nbsp;</pre>
<p>or</p>
<pre class="haskell">&nbsp;
runContT :: ContT r m a -&gt; m r
runContT <span style="color: green;">&#40;</span>ContT m<span style="color: green;">&#41;</span> = m <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a>
&nbsp;</pre>
<p><code>ContT</code> and <code>Codensity</code> both yield a result in which all of the uses of the underlying monad's <code>(>>=)</code> are right associated.</p>
<p>This can be convenient for two reasons:</p>
<p>First, some almost-monads are not associative, and converting to ContT or Codensity can be used to fix this fact. </p>
<p>Second, in many monads, when you build a big structure using left associated binds, like:</p>
<pre class="haskell">&nbsp;
    <span style="color: green;">&#40;</span>f &gt;&gt;= g<span style="color: green;">&#41;</span> &gt;&gt;= h
&nbsp;</pre>
<p>rather than use right associated binds like</p>
<pre class="haskell">&nbsp;
   f &gt;&gt;= \x -&gt; g x &gt;&gt;= h
&nbsp;</pre>
<p>then you wind up building a structure, then tearing it down and building up a whole new structure. This can compromise the productivity of the result, and it can also affect the asymptotic performance of your code. </p>
<p>Even though the monad laws say these two yield the same answer.</p>
<p><strong>The dual of substitution is redecoration</strong></p>
<p>To see that, first, it is worth noting that about ten years back, Tarmo Uustalu and Varmo Vene wrote "<a href="http://www.ioc.ee/~tarmo/papers/sfp01-book.pdf">The dual of substitition is redecoration</a>", which among other things quite eloquently described how monads are effectively about substituting new tree-like structures, and then renormalizing.</p>
<p>This can be seen in terms of the more categorical viewpoint, where we define a monad in terms of <code>return</code>, <code>fmap</code> and <code>join</code>, rather than <code>return</code> and <code>(>>=)</code>. In that presentation:</p>
<pre class="haskell">&nbsp;
m &gt;&gt;= f = join <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f m<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p><code>fmap</code> is performing substitution. and <code>join</code> is dealing with any renormalization.</p>
<p>Done this way, <code>(m >>= f)</code> on the <code>Maybe</code> monad would first <code>fmap</code> to obtain <code>Just (Just a)</code>, <code>Just Nothing</code> or <code>Nothing</code> before flattening.</p>
<p>In the Maybe a case, the association of your binds is largely immaterial, the normalization pass fixes things up to basically the same size, but in the special case of a free monad the monad is <strong>purely defined in terms of substitution</strong>, since:</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- join :: Functor f =&gt; Free f (Free f a) -&gt; Free f a</span>
<span style="color: #5d478b; font-style: italic;">-- join (Pure a) = a</span>
<span style="color: #5d478b; font-style: italic;">-- join (Free as) = Free (fmap join as)</span>
&nbsp;</pre>
<p>This means that every time you <code>>>=</code> a free monad you are accumulating structure -- structure that you have traverse past to deal with subsequent left-associated invocations of <code>>>=</code>! Free monads never shrink after a bind and the main body of the tree never changes.</p>
<p>More concretely, you could build a binary tree with</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- data Tree a = Tip a | Bin (Tree a) (Tree a)</span>
&nbsp;</pre>
<p>and make a monad out of it, writing out your <code>return</code> and <code>(>>=)</code>, etc. by hand</p>
<p>The same monad could be had 'for free' by taking the free monad of</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Bin a = Bin a a
    <span style="color: #06c; font-weight: bold;">deriving</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a>, Foldable, Traversable<span style="color: green;">&#41;</span>
    <span style="color: #5d478b; font-style: italic;">-- using LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable</span>
&nbsp;</pre>
<p>yielding the admittedly slightly less convenient type signature</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Tree = Free Bin
&nbsp;</pre>
<p>Now you can use <code>return</code> for <code>Tip</code>, and </p>
<pre class="haskell">&nbsp;
bin :: MonadFree Bin m =&gt; m a -&gt; m a -&gt; m a
bin l r = wrap <span style="color: green;">&#40;</span>Bin l r<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>to construct a binary tree node, using any free monad representation.</p>
<p>Now, if that representation is <code>Free Bin</code> (or the original more direct <code>Tree</code> type above) then code that looks like <code>f >>= \x -> g x >>= h</code> performs fine, but <code>(f >>= g) >>= h</code> will retraverse the unchanging 'trunk' of the tree structure twice. That isn't so bad, but given n uses of >>= we'll traverse an ever-growing trunk over and over <em>n</em> times!</p>
<p><strong>Putting Codensity to Work</strong></p>
<p>But, we have a tool that can fix this, <code>Codensity</code>! </p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> MonadFree f m =&gt; MonadFree f <span style="color: green;">&#40;</span>Codensity m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  wrap t = Codensity <span style="color: green;">&#40;</span>\h -&gt; wrap <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>\p -&gt; runCodensity p h<span style="color: green;">&#41;</span> t<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Janis packaged up the use of <code>Codensity</code> into a nice combinator that you can sprinkle through your code, so that your users never need know it exists. Moreover, it prevents them from accidentally using any of the extra power of the intermediate representation. If your code typechecks before you use improve somewhere within it, and it type checks after, then it will yield the same answer.</p>
<pre class="haskell">&nbsp;
improve :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> m. MonadFree f m =&gt; m a<span style="color: green;">&#41;</span> -&gt; Free f a
improve m = lowerCodensity m
&nbsp;</pre>
<p>By now, it should be clear that the power of <code>Codensity</code> is sufficient to the task, but is it necessary?</p>
<p>More Soon.</p>
<p>[Edit; Fixed minor typographical errors pointed out by ShinNoNoir, ivanm, and Josef Svenningsson, including a whole bunch of them found by Noah Easterly]</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2011/free-monads-for-less/feed/</wfw:commentRss>
		<slash:comments>399</slash:comments>
		</item>
		<item>
		<title>Introducing Speculation</title>
		<link>http://comonad.com/reader/2010/introducing-speculation/</link>
		<comments>http://comonad.com/reader/2010/introducing-speculation/#comments</comments>
		<pubDate>Thu, 22 Jul 2010 19:53:03 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Boston Haskell]]></category>
		<category><![CDATA[Haskell]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=205</guid>
		<description><![CDATA[A couple of days ago, I gave a talk at Boston Haskell about a shiny new speculative evaluation library, speculation on hackage, that I have implemented in Haskell. The implementation is based on the material presented as "Safe Programmable Speculative Parallelism" by Prakash Prabhu, G Ramalingam, and Kapil Vaswani at last month's PLDI.
I've uploaded a [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of days ago, I gave a talk at Boston Haskell about a shiny new speculative evaluation library, <a href="http://hackage.haskell.org/package/speculation">speculation</a> on hackage, that I have implemented in Haskell. The implementation is based on the material presented as <a href="http://research.microsoft.com/apps/pubs/default.aspx?id=118795">"Safe Programmable Speculative Parallelism"</a> by Prakash Prabhu, G Ramalingam, and Kapil Vaswani at last month's PLDI.</p>
<p>I've uploaded a copy of my slides here:</p>
<p>* Introducing Speculation [<a href='http://comonad.com/reader/wp-content/uploads/2010/07/Speculation.pptx'>PowerPoint</a> | <a href='http://comonad.com/reader/wp-content/uploads/2010/07/Speculation.pdf'>PDF</a>]</p>
<p><span id="more-205"></span></p>
<p>This package provides speculative function application and speculative folds. Speculative STM transactions take the place of the transactional rollback machinery from the paper, but transactions are not always required in pure code. To get a feel for the shape of the library, here is an excerpt from the <a href="http://hackage.haskell.org/package/speculation">documentation</a> for one of the combinators:</p>
<blockquote><p>
<code><br />
     spec :: Eq a => a -> (a -> b) -> a -> b<br />
</code></p>
<p><code>spec g f a</code> evaluates <code>f g</code> while forcing <code>a</code>, if <code>g == a</code> then <code>f g</code> is returned, otherwise <code>f a</code> is evaluated and returned. Furthermore, if the argument has already been evaluated, we skip the <code>f g</code> computation entirely. If a good guess at the value of <code>a</code> is available, this is one way to induce parallelism in an otherwise sequential task. However, if the guess isn't available more cheaply than the actual answer, then this saves no work and if the guess is wrong, you risk evaluating the function twice. Under high load, since <code>f g</code> is computed via the spark queue, the speculation will be skipped and you will obtain the same answer as <code>f $! a</code>.
</p></blockquote>
<p>ASCII art time-lines of how this can speed up evaluation are available in both the slides and the documentation linked to above, but assuming an otherwise serial problem, you effectively wager otherwise idle CPU time and the time to generate your guess on the quality of your guess.</p>
<p>Note that <a href="http://hackage.haskell.org/trac/ghc/ticket/4167">numSparks# feature request</a> that was mentioned in the slides has already been implemented in GHC HEAD, and support shall be added to improve the performance of the speculative STM transactions under high load as mentioned in the slides.</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2010/introducing-speculation/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>
