<?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>Mathematics and Computation &#187; monad</title>
	<atom:link href="http://math.andrej.com/tag/monad/feed/" rel="self" type="application/rss+xml" />
	<link>http://math.andrej.com</link>
	<description>Mathematics for computers</description>
	<lastBuildDate>Thu, 05 Apr 2012 20:51:32 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4-beta2-20500</generator>
		<item>
		<title>A Haskell monad for infinite search in finite time</title>
		<link>http://math.andrej.com/2008/11/21/a-haskell-monad-for-infinite-search-in-finite-time/</link>
		<comments>http://math.andrej.com/2008/11/21/a-haskell-monad-for-infinite-search-in-finite-time/#comments</comments>
		<pubDate>Fri, 21 Nov 2008 21:57:08 +0000</pubDate>
		<dc:creator>Martin Escardo</dc:creator>
				<category><![CDATA[Computation]]></category>
		<category><![CDATA[Constructive math]]></category>
		<category><![CDATA[Guest post]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[monad]]></category>

		<guid isPermaLink="false">http://math.andrej.com/?p=122</guid>
		<description><![CDATA[<p>I show how monads in Haskell can be used to structure infinite search algorithms, and indeed get them for free. This is a follow-up to my blog post Seemingly impossible functional programs. In the two papers Infinite sets that admit fast exhaustive search (LICS07) and Exhaustible sets in higher-type computation (LMCS08), I discussed what kinds of [...]]]></description>
			<content:encoded><![CDATA[<p>I show how monads in Haskell can be used to structure infinite search algorithms, and indeed get them for free. This is a follow-up to my blog post <a href="http://math.andrej.com/2007/09/28/seemingly-impossible-functional-programs/">Seemingly impossible functional programs</a>. In the two papers <a href="http://www.cs.bham.ac.uk/~mhe/papers/exhaustive.pdf">Infinite sets that admit fast exhaustive search</a> (LICS07) and <a href="http://www.lmcs-online.org/ojs/viewarticle.php?id=395&amp;layout=abstract">Exhaustible sets in higher-type computation</a> (LMCS08), I discussed what kinds of infinite sets admit exhaustive search in finite time, and how to systematically build such sets. Here I build them using monads, which makes the algorithms more transparent (and economic).<span id="more-122"></span></p>
<h3>An abstract data type for searchable sets</h3>
<p>I want to define a Haskell type constructor <code>S</code> such that, for any type <code>a</code>, the elements of type <code>S a</code> are the searchable subsets of <code>a</code>. Thus, <code>S</code> is like the powerset constructor in set theory, except that not all subsets are allowed here. Like the powerset construction, <code>S</code> will be a monad. Before implementing <code>S</code> concretely, I list the operations I would like to be able to perform with searchable sets:</p>
<pre>search :: S a -&gt; (a -&gt; Bool) -&gt; Maybe a
image :: (a -&gt; b) -&gt; S a -&gt; S b
singleton :: a -&gt; S a
union :: S a -&gt; S a -&gt; S a
bigUnion :: S(S a) -&gt; S a</pre>
<p>I adopt the notational convention, borrowed from the list data type, that if <code>x</code> is used to denote an element of type <code>a</code> then the plural <code>xs</code> is used to denote a searchable set of elements of <code>a</code>. So, notationally speaking, if <code>x :: a</code> then <code>xs :: S a</code>.</p>
<p>Given a set <code>xs :: S a</code> and a predicate <code>p :: a -&gt; Bool</code>, we require that the expression <code>search xs p</code> either produces<code> Just</code> an example of some <code>x :: a</code> in the set<code> xs :: S a</code> with <code>p x = True</code>, if such an element exists, or else <code>Nothing</code>. For a function <code>f :: a -&gt; b</code> and a set <code>xs :: S a</code>, the expression <code>image f xs</code> denotes the<code> f</code>-image of the set <code>xs</code> in the sense of set theory, that is, the set <code>ys :: S b</code> such that <code>y</code> $\in$ <code>ys</code> iff <code>f(x)=y</code> for some <code>x</code> $\in$ <code>xs</code>. The other operations construct singletons, binary unions, and unions of sets of sets, also in the usual sense of set theory.</p>
<h3>The monad</h3>
<p>It is defined from the abstract data type as</p>
<pre>instance Monad S where
  return = singleton
  xs &gt;&gt;= f = bigUnion(image f xs)</pre>
<p>Notice that <code>xs :: S a</code> and <code>f :: a -&gt; S b</code>, and hence<code> image f xs :: S S b</code>.</p>
<h3>Consequences of having a monad</h3>
<p>Finite products of searchable sets are searchable:</p>
<pre>times :: S a -&gt; S b -&gt; S(a,b)
xs `times` ys = do x &lt;- xs
                   y &lt;- ys
                   return(x,y)</pre>
<p>That is, the elements of the set <code>xs `times` ys</code> are the pairs<code> (x,y)</code> with <code>x</code> $\in$ <code>xs</code> and <code>y</code> $\in$ <code> ys</code>. This turns out to be the same algorithm given in the above two papers, although the definition given there looks very different as it doesn&#8217;t use monads.</p>
<p>Using lazy lists, the binary product can be iterated to finite and infinite products as follows:</p>
<pre>product :: [S a] -&gt; S[a]
product [] = return []
product (xs:yss) = do x &lt;- xs
                      ys &lt;- product yss
                      return(x:ys)</pre>
<p>Notice that</p>
<ol>
<li> <code>xs :: S a</code> is a set,</li>
<li><code>x :: a</code> is an element of <code>xs</code>,</li>
<li><code>yss :: [S a]</code> is a list of sets,</li>
<li><code>product yss :: S[a]</code> is a set of lists,</li>
<li><code>ys :: [a]</code> is a list.</li>
</ol>
<p>Again, this turns out to be the same infinite product algorithm given in the above papers, more precisely the one given in<a href="http://www.cs.bham.ac.uk/~mhe/papers/exhaustive.pdf"> [LICS07]</a>, page 9, or<a href="http://www.lmcs-online.org/ojs/viewarticle.php?id=395&amp;layout=abstract"> [LMCS08]</a>, Section 8.1. I am working on a paper addressed to the Haskell and functional programming communities that will spell out this and other claims and details.</p>
<h4>Haskell&#8217;s sequence<tt></tt></h4>
<p>However, there is no need to define <code>product</code>, because it is already defined in the<a href="http://www.haskell.org/onlinereport/standard-prelude.html"> Haskell&#8217;98 Standard Prelude</a> under the name <code>sequence</code> (using <code>foldr</code> and the monad operations rather than recursion and do-notation, but this makes no difference), and moreover for any monad, not just<code> S</code>.</p>
<h4>Example</h4>
<p>The Cantor space of infinite sequences of binary digits, discussed in the previous blog post, can be constructed as follows:</p>
<pre>bit :: S Int
bit = singleton 0 `union` singleton 1

cantor :: S [Int]
cantor = sequence (repeat bit)</pre>
<p>This amounts to</p>
<blockquote><p><code>cantor</code> = <code>bit</code> $\times$ <code>bit</code> $\times$ <code>bit</code> $\times \dots$
</p></blockquote>
<h3>Quantifiers</h3>
<p>Notice that we can existentially and universally quantify over searchable sets in an algorithmic fashion, even when they are infinite, as is the case for the Cantor space:</p>
<pre>forsome, forevery :: S a -&gt; (a -&gt; Bool) -&gt; Bool
forsome xs p = case search xs p of
                 Nothing -&gt; False
                 Just _ -&gt; True
forevery xs p = not(forsome xs (\x -&gt; not(p x))</pre>
<p>Here <code>forsome xs</code> and <code>forevery xs</code> quantify over the set <code>xs</code>:</p>
<ol>
<li> <code>forsome xs p = True</code> iff <code>p x = True</code> for some<code> x</code> $\in$ <code>xs</code>,</li>
<li><code>forevery xs p = True</code> iff <code>p x = True</code> for every<code> x</code> $\in$ <code>xs</code>.</li>
</ol>
<p>(The function <code>forsome</code> is in fact a monad morphism from <code>S</code> into the continuation monad.)</p>
<h4>Contrived examples that nevertheless make a point</h4>
<p>Consider the program</p>
<pre>f :: Int -&gt; Int -&gt; Int -&gt; Int
f n2 n1 n0 = 4 * n2 + 2 * n1 + n0

p :: Int -&gt; Bool
p k = forevery cantor (\xs -&gt;
       forsome cantor (\ys -&gt;
         f (xs !! 10) (xs !! 100) (xs !! 1000) ==
         k - f (ys !! 2000) (ys !! 200) (ys !! 20)))</pre>
<p>Then the expressions <code>p 6</code>, <code>p 7</code> and <code>p 8</code> evaluate to<code> False</code>, <code>True</code> and <code>False</code> respectively, together in a fraction of a second using the Glasgow Haskell Interpreter<code> ghci</code>, using our implementation of the abstract data type<code> S</code> given below.</p>
<p>As another example, consider</p>
<pre>q = forevery cantor (\us -&gt;
     forsome cantor (\vs -&gt;
      forevery cantor (\xs -&gt;
       forsome cantor (\ys -&gt;
        us !! 333 + xs !! 17000 ==
        vs !! 3000 * ys !! 1000))))</pre>
<p>Then <code>q</code> evaluates to <code>True</code> in less than a second.</p>
<p>These examples are certainly contrived, but they do illustrate that something non-trivial is going on from an algorithmic point of view, as the quantification algorithms have no access to the source code of the predicates they apply to. I&#8217;ll discuss more meaningful examples another time. (I can use the quantifiers to find bugs in programs for exact real number computation using infinite lazy lists of digits. An application by <a href="http://homepages.inf.ed.ac.uk/als/">Alex Simpson</a> to integration was mentioned in the previous post.)</p>
<h3>Representation of searchable sets</h3>
<p>How should we represent infinite searchable sets to get an implementation of our abstract data type?</p>
<h4>Obstacles</h4>
<p>An infinite searchable set can be uncountable, like the Cantor space, and hence we cannot implement it using a lazy list of its elements. Moreover, this wouldn&#8217;t help regarding exhaustive search in finite time. It can be argued that the <em>computable</em> elements of the Cantor space form a countable set. However, they are not <em>computably countable</em> (or r.e.), with the very same proof given by Cantor in the non-computable case, by diagonalization. (Exercise: write a Haskell program that given any infinite lazy list of elements of the Cantor space, produces an element that is not in the list. This amounts to an implementation of Cantor&#8217;s proof of the non-denumerability of the Cantor space.)</p>
<h4>Almost a solution</h4>
<p>The crucial operation we can perform with a searchable set is to search it. Hence it is natural to represent a searchable set by a search function. The following is what this line of reasoning tempted me to do at the beginning of this work:</p>
<pre>newtype S a = S {search :: (a -&gt; Bool) -&gt; Maybe a}</pre>
<p>or, equivalently,</p>
<pre>newtype S a = S ((a -&gt; Bool) -&gt; Maybe a)
search :: S a -&gt; (a -&gt; Bool) -&gt; Maybe a
search(S searcher) = searcher</pre>
<p>This has the advantage that it accounts for the empty set. However, this breaks the theorem that countable products of searchable sets are searchable, precisely because the empty set is present. In fact, if one of the factors is empty, then the product is empty. But an empty set may be present arbitrarily far away in the lazy list of sets, and the search algorithm can only output the first element of the lazy list when it knows that the product is non-empty. Hence it can never output it, because it can never determine non-emptiness of the product. In practice, we get an infinite loop when we run the product algorithm <code>sequence</code> if we work with the above implementation of <code>S</code>. However, with the exception of countable products, everything we do here works with the above implementation. But infinite products is what is needed to get infinite searchable sets.</p>
<h4>The solution</h4>
<p>Hence we do as we did in the above two papers instead:</p>
<pre>newtype S a = S {find :: (a -&gt; Bool) -&gt; a}</pre>
<p>or, equivalently,</p>
<pre>newtype S a = S ((a -&gt; Bool) -&gt; a)
find :: S a -&gt; (a -&gt; Bool) -&gt; a
find(S finder) = finder</pre>
<p>This forces the sets to be non-empty, but has a defect: it also forces the <code>find</code> operator to tell lies when there is no correct element it can choose. We impose a requirement to overcome this: although lies are allowed, one always must have that <code>find xs p</code> chooses an element in the set <code>xs</code>, and if there is an element <code>x</code> $\in$ <code>xs</code> with <code>p(x)=True</code>, then the answer must be honest. Given this requirement, we can easily check whether <code>find</code> is lying, and this is what I do in the implementation of <code>search</code>:</p>
<pre>search :: S a -&gt; (a -&gt; Bool) -&gt; Maybe a
search xs p = let x = find xs p
              in if p x then Just x else Nothing</pre>
<p>With this representation of searchable sets, we have a shortcut for the implementation of the existential quantifier</p>
<pre>forsome :: S a -&gt; (a -&gt; Bool) -&gt; Bool
forsome xs p = p(find xs p)</pre>
<p>Also notice that the above implementation of <code>search</code> is equivalent to</p>
<pre>search xs p = if forsome xs p then Just(find xs p) else Nothing</pre>
<h3>Implementation of the abstract data type</h3>
<p>Given the above representation of searchable sets, we have already implemented the first of the operations that define our abstract data type:</p>
<pre>search :: S a -&gt; (a -&gt; Bool) -&gt; Maybe a
image :: (a -&gt; b) -&gt; S a -&gt; S b
singleton :: a -&gt; S a
union :: S a -&gt; S a -&gt; S a
bigUnion :: S(S a) -&gt; S a</pre>
<p>The others can be implemented as follows:</p>
<pre>image :: (a -&gt; b) -&gt; S a -&gt; S b
image f xs = S(\q -&gt; f(find xs (\x -&gt; q(f x))))</pre>
<p>That is, given a predicate <code>q :: b -&gt; Bool</code>, to find <code>y</code> $\in$ <code>f(xs)</code> such that <code>q(y)</code> holds, first find <code>x</code> $\in$ <code>xs</code> such that <code>q(f x)</code> holds, and then apply <code>f</code> to this <code>x</code>.</p>
<pre>singleton :: a -&gt; S a
singleton x = S(\p -&gt; x)</pre>
<p>Given the requirement of the previous section, we can only answer <code>x</code>, and this is what we do. To implement binary unions, I first implement doubletons, and then reduce to arbitrary unions:</p>
<pre>doubleton :: a -&gt; a -&gt; S a
doubleton x y = S(\p -&gt; if p x then x else y)

union :: S a -&gt; S a -&gt; S a
xs `union` ys = bigUnion(doubleton xs ys)</pre>
<p>Arbitrary unions are a bit trickier:</p>
<pre>bigUnion :: S(S a) -&gt; S a
bigUnion xss = S(\p -&gt; find(find xss (\xs -&gt; forsome xs p)) p)</pre>
<p>By definition of union, as in set theory, <code>x</code> $\in \bigcup$ <code>xss</code>  $\iff \exists$ <code>xs</code> $\in$ <code>xss</code> such that <code>x</code> $\in$ <code>xs</code>. What our definition says is that, in order to find <code>x</code> $\in \bigcup$ <code>xss</code> such that <code>p(x)</code> holds, we first find <code>xs</code> $\in$ <code>xss</code> such that <code>p(x)</code> holds for some <code>x</code> $\in$ <code>xs</code>, and then find a specific <code>x</code> $\in$ <code>xs</code> such that <code>p(x)</code> holds.</p>
<h3>That&#8217;s it, we are done</h3>
<p>It remains to make a few remarks. After them you&#8217;ll find the complete Haskell program, which is embarrassingly short in comparison with the size of this post.</p>
<h3>Algorithms for free</h3>
<p>There is a Haskell program called <a href="http://permalink.gmane.org/gmane.comp.lang.haskell.general/12747">Djinn</a> that, given a Haskell type, automatically gives you a recursion-free Haskell program of that type, provided there is some, and lets you know if there isn&#8217;t any. All the programs discussed here are correctly guessed by Djinn, just from knowledge of their types, except the binary and infinite product algorithms. For the binary product, Djinn gives four guesses. Only two of them are product algorithms, and one of them is equivalent to the one we have defined (the other is the symmetric version). The infinite product is hopeless, because it crucially relies on recursion. But singleton, image and big union are correctly guessed, with a unique guess each. Moreover, Djinn can directly guess the monad structure, in the sense of Haskell, without the detour via singleton, image and big union, which amount to the definition of monad in the sense of category theory.</p>
<p>Thus, all we have to do in principle is to define the type constructor <code>S</code> of the monad: once we have done that, Djinn can tell us what the monad operations are, and the Haskell prelude gives us the infinite product algorithm <code>sequence</code>. But this is not what happened historically. And of course, once we do have the product algorithm, we have to show that it does accomplish what we claim. The proof is tricky, and is developed in the above two papers, where the first gives a sketch and the second gives complete details.</p>
<h3>The monad laws</h3>
<p>The monad laws are rather laborious to prove. Hence I wrote a <a href="/wp-content/uploads/2008/11/proof.hs">Haskell program</a> that wrote <a href="/wp-content/uploads/2008/11/proof-output">the proof</a> for me, as follows. The laws are a set of equations. To prove each one, I calculate the normal form of each side of the equation, and check that they are the same except perhaps for the name of the bound variables. The output of the Haskell program is five pages of chains of equations that one can routinely check if one wants to. Presumably I could have done this using a proof assistant, but I found it quicker to write a proof generator for this specific theorem than to familiarize myself with proof assistants (shame on me).</p>
<p>There are two interesting aspects of the monad <code>S</code> that become apparent when we develop this proof: (1) Not all elements of <code>S a</code> are search functions, but nevertheless the monad laws hold even when the &#8220;junk&#8221; elements of <code>S a</code> are taken into account. (2) The type of booleans in the definition of <code>S</code> can be replaced by any type whatsoever and the monad laws still hold. This second point brings me to my final comment.</p>
<h3>Bar recursion</h3>
<p>Before I made the connection with monads <a href="http://www.cs.bham.ac.uk/~mhe/papers/selection.pdf">earlier this year</a>, <a href="http://www.dcs.qmul.ac.uk/~pbo/">Paulo Oliva</a> discovered that the product algorithm given in <a href="http://www.cs.bham.ac.uk/~mhe/papers/exhaustive.pdf">[LICS07]</a> is a manifestation of bar recursion, provided we replace the booleans by the integers. See his papers at his web page to get an idea of what bar recursion is and what its applications are. Now, putting this together with the above findings, it follows that the Haskell prelude function <code>sequence</code> turns out to be a form of bar recursion (technically known as modified bar recursion). Paulo and I have been working together trying to clarify all these connections from a theoretical point of view, and we are writing a paper with these and other findings, this time addressed to the theoretical computer science and logic communities.</p>
<h3>The complete program</h3>
<p>I summarize and rearrange the code discussed above, without the contrived examples:</p>
<pre>newtype S a = S {find :: (a -&gt; Bool) -&gt; a}

search :: S a -&gt; (a -&gt; Bool) -&gt; Maybe a
search xs p = let x = find xs p in if p x then Just x else Nothing

forsome, forevery :: S a -&gt; (a -&gt; Bool) -&gt; Bool
forsome xs p = p(find xs p)
forevery xs p = not(forsome xs (\x -&gt; not(p x)))

singleton :: a -&gt; S a
singleton x = S(\p -&gt; x)

doubleton :: a -&gt; a -&gt; S a
doubleton x y = S(\p -&gt; if p x then x else y)

image :: (a -&gt; b) -&gt; S a -&gt; S b
image f xs = S(\q -&gt; f(find xs (\x -&gt; q(f x))))

bigUnion :: S(S a) -&gt; S a
bigUnion xss = S(\p -&gt; find(find xss (\xs -&gt; forsome xs p)) p)

union :: S a -&gt; S a -&gt; S a
xs `union` ys = bigUnion(doubleton xs ys)

instance Monad S where
  return = singleton
  xs &gt;&gt;= f = bigUnion(image f xs)

times :: S a -&gt; S b -&gt; S(a,b)
xs `times` ys = do x &lt;- xs
                   y &lt;- ys
                   return(x,y)

bit :: S Int
bit = doubleton 0 1

cantor :: S [Int]
cantor = sequence (repeat bit)</pre>
<h3>The making of this work</h3>
<p>Here is how I came up with the idea of using monads for this purpose. It emerged from the above two papers, and from the ealier <a href="http://www.sciencedirect.com/science?_ob=ArticleURL&amp;_udi=B75H1-4DTKG8R-3&amp;_user=10&amp;_rdoc=1&amp;_fmt=&amp;_orig=search&amp;_sort=d&amp;view=c&amp;_acct=C000050221&amp;_version=1&amp;_urlVersion=0&amp;_userid=10&amp;md5=d886d0ea55964190ad6843f28527c49d">Barbados notes</a>, that searchable sets are compact in the sense of topology. And I was familiar, from denotational semantics, domain theory and topology, with a number of monads of compact sets, notably the Smyth powerdomain monad and the Vietoris hyperspace modad. So although this took some time to mature and be realized, it was inevitable.</p>
<p>What was a surprise to me is that this monadic view of searchable sets shows that the countable product functional, which implements the countable Tychonoff theorem from topology, and which amounts to modified bar recursion from logic in view of Paulo&#8217;s discovery (which is in itself a surprise), found its way independently in Haskell via the standard prelude function <code>sequence</code>. I don&#8217;t know whether <code>sequence</code> was originally intended to be applied to infinite lists, but it can, and moreover in an interesting way. However, for most monads I considered, including the continuation monad and of course excluding the search monad, the functional <code>sequence</code> applied to an infinite list gives rise to a divergent computation.</p>
]]></content:encoded>
			<wfw:commentRss>http://math.andrej.com/2008/11/21/a-haskell-monad-for-infinite-search-in-finite-time/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Not all computational effects are monads</title>
		<link>http://math.andrej.com/2008/11/17/not-all-computational-effects-are-monads/</link>
		<comments>http://math.andrej.com/2008/11/17/not-all-computational-effects-are-monads/#comments</comments>
		<pubDate>Mon, 17 Nov 2008 12:53:32 +0000</pubDate>
		<dc:creator>Andrej Bauer</dc:creator>
				<category><![CDATA[Computation]]></category>
		<category><![CDATA[catch]]></category>
		<category><![CDATA[computational effect]]></category>
		<category><![CDATA[monad]]></category>
		<category><![CDATA[timeout]]></category>

		<guid isPermaLink="false">http://math.andrej.com/?p=109</guid>
		<description><![CDATA[<p>Lately I&#8217;ve been thinking about computational effects in general, i.e., what is the structure of the &#8220;space of all computational effects&#8221;. We know very little about this topic. I am not even sure we know what &#8220;the space of all computational effects&#8221; is. Because Haskell is very popular and in Haskell computational effects are expressed as [...]]]></description>
			<content:encoded><![CDATA[<p>Lately I&#8217;ve been thinking about computational effects <em>in general</em>, i.e., what is the structure of the &#8220;space of all computational effects&#8221;. We know very little about this topic. I am not even sure we know what &#8220;the space of all computational effects&#8221; is. Because Haskell is very popular and in Haskell computational effects are expressed as monads, many people might think that I am talking about the space of all monads. But I am not, and in this post I show two computational effects which are not of the usual Haskell monad kind. They should present a nice programming challenge to Haskell fans.<span id="more-109"></span></p>
<p>Computational effects are things like non-termination, exceptions, state, input/output, continuations, non-determinism, and others. In Haskell these are represented as monads, and in fact there is a whole <a href="http://sigfpe.blogspot.com/">industry of Haskell monads</a>. But how about the following two examples?</p>
<h3>Catch</h3>
<p>First we fix a particular operational semantics for (pure) Haskell so that the order of execution is determined (of course, from within pure Haskell we cannot detect the order). We now adjoin to Haskell a new constant</p>
<blockquote><p><code>catch :: ((a -&gt; b) -&gt; c) -&gt; Maybe a </code></p></blockquote>
<p>which allows us to detect the fact that a function is evaluated at an argument. More precisely, given any</p>
<blockquote><p><code>f :: (a -&gt; b) -&gt; c</code></p></blockquote>
<p><code>catch f</code> inspects evaluation of <code>f g</code> where the argument <code>g :: a -&gt; b</code> is specially crafted so that:</p>
<ul>
<li>if <code>f</code> attempts to evaluate <code>g</code> at an argument <code>x</code> then <code>catch f</code> evaluates to <code>Just x</code>,</li>
<li>otherwise, if <code>f</code> evaluates to a result without ever evaluating <code>g</code> at any argument then <code>catch f</code> evaluates to <code>Nothing</code>, and</li>
<li>if <code>f</code> diverges without evaluating <code>g</code> then <code>catch f</code> diverges, also.</li>
</ul>
<p>For example:</p>
<ul>
<li><code>catch (\g -&gt; 42)</code> evaluates to <code>Nothing</code></li>
<li><code>catch (\g -&gt; \x -&gt; g (g x))</code> evaluates to <code>Nothing</code></li>
<li><code>catch (\g -&gt; g 1 + g 2)</code> evaluates to <code>Just 1</code>, assuming that + is evaluated from left to right.</li>
</ul>
<p>With access to the underlying Haskell compiler or interpreter we could implement <code>catch</code>. We can also <em>simulate</em> <code>catch</code> within Haskell using exceptions. The idea is quite simple: <code>catch f</code> passes to <code>f</code> a function which raises an exception when it is evaluated, then <code>catch</code> intercepts the exception. Like this:</p>
<blockquote>
<pre>module Katch where

-- In order to avoid conflicts with Haskell's Prelude.catch we
-- call our function "katch"

-- To keep things self-contained, we define our own mini exception monad

data Exception e a = Success a | Failure e deriving Show

instance Monad (Exception e) where
    return = Success
    (Failure x) &gt;&gt;= _   = Failure x
    (Success x) &gt;&gt;= f   = f x

throw :: e -&gt; Exception e a
throw = Failure

intercept :: Exception e a -&gt; (e -&gt; a) -&gt; a
intercept (Success x) _ = x
intercept (Failure x) h = h x

-- Now we may simulate catch by throwing an exception and intercepting it.
-- Of course, the type of katsch reflects the fact that exceptions are used
-- under the hood.

katsch :: ((a -&gt; Exception a b) -&gt; Exception a c) -&gt; Maybe a
katsch f = intercept
           (do y &lt;- f (\x -&gt; throw x)
               return Nothing)
           (\x -&gt; Just x)

-- Examples (must now be written in monadic style)
a = katsch (\g -&gt; return 42)                      -- Nothing
b = katsch (\g -&gt; return (\x -&gt; do y &lt;- g x       -- Nothing
                                   z &lt;- g y
                                   return z))
c = katsch (\g -&gt; do x &lt;- g 1;                    -- Just 1
                     y &lt;- g 2;
                     return (x + y))</pre>
</blockquote>
<p>This works but is unsatisfactory. I don&#8217;t want to simulate <code>catch</code> with exceptions. Is there a way to do <code>catch</code> directly? I do not know, since it is not even clear to me that we have a monad.</p>
<h3>Timeout</h3>
<p>The second example is easier to understand than the first one. Assume we have an operational semantics of Haskell in which it is possible to count steps of execution. Exactly what is &#8220;one step&#8221; does not matter. The important thing is that a diverging computation has infinitely many steps, whereas a terminating one has finitely many steps. Define a special operation</p>
<blockquote><p><code>timeout :: Integer -&gt; a -&gt; Maybe a</code></p></blockquote>
<p>such that <code>timeout k e</code> evaluates to <code>Just v</code> if <code>e</code> evaluates to <code>v</code> in at most <code>k</code> steps of execution, and to <code>Nothing</code> if evaluation of <code>e</code> takes more than <code>k</code> steps. This could be implemented in an interpreter or compiler by keeping a counter of execution steps (we would actually need a stack of counters, one for each invocation of timeout).</p>
<p>Here is an attempt to implement timeout as a Haskel monad (think of the clock &#8220;ticking&#8221; when you read the code):</p>
<blockquote>
<pre>module Timeout where

-- We represent values together with number of steps needed to compute them
data Timeout a = Ticks (Integer, a)

tick x = Ticks (1, x)

instance Monad (Timeout) where
    return               = tick
    Ticks (j, x) &gt;&gt;= f   = let Ticks (k, y) = f x in Ticks (1+j+k, y)

timeout :: Integer -&gt; Timeout a -&gt; Maybe a
timeout n a = let Ticks (k, v) = a in
              if k &lt;= n then Just v else Nothing

-- Examples
a = timeout 4 (do x &lt;- tick 7      -- Nothing
                  y &lt;- tick 5
                  return (x + y))

b = timeout 5 (do x &lt;- tick 7      -- Just 12
                  y &lt;- tick 5
                  return (x + y))

-- This example should evaluate to Nothing
c = timeout 5 (omega 0) where omega n = do m &lt;- tick (n+1)
                                           omega m</pre>
</blockquote>
<p>It is understandable, albeit annoying, that we have to &#8220;tick&#8221; basic computation steps explicitly. But the real trouble is that the last example diverges when it should evaluate to <code>Nothing</code>. This is happening because the monad just counts steps of execution without ever aborting evaluation. What we really need is a monad which stops the execution when the allowed number of steps has been reached. I think this can be done, and I hope someone will tell me how, myabe with a <a href="http://www.cs.helsinki.fi/u/ekarttun/comonad/">comonad</a> or <a href="http://www.haskell.org/arrows/">some such</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://math.andrej.com/2008/11/17/not-all-computational-effects-are-monads/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
	</channel>
</rss>

