<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<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/"
	>

<channel>
	<title>monads &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://wordpress.com/tag/monads/</link>
	<description>Feed of posts on WordPress.com tagged "monads"</description>
	<pubDate>Mon, 08 Sep 2008 13:03:11 +0000</pubDate>

	<generator>http://wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[We're BACK!]]></title>
<link>http://toetapsandspasticclaps.wordpress.com/?p=330</link>
<pubDate>Sat, 23 Aug 2008 22:25:12 +0000</pubDate>
<dc:creator>Sanita</dc:creator>
<guid>http://toetapsandspasticclaps.wordpress.com/?p=330</guid>
<description><![CDATA[
It&#8217;s been a helluva a while since we updated this thing.  Alison and I just moved in to our ]]></description>
<content:encoded><![CDATA[<p><a href="http://agonist.org/schecter/wp-content/uploads/2008/05/moving-full.jpg"><img class="aligncenter" src="http://agonist.org/schecter/wp-content/uploads/2008/05/moving-full.jpg" alt="" width="310" height="341" /></a></p>
<p>It's been a helluva a while since we updated this thing.  Alison and I just moved in to our new abodes and it's looking quite snazzy.  So we are READY for this school year and we hope you are too.  I just wanted to let you guys know that you will probably find us tonight at <a href="http://stlouis.metromix.com/events/fair_festival/the-lot-festival-downtown-west/534499/content" target="_blank">THE LOT Festival</a> at The Schlafly Tap Room.  The show begins at 4pm with <a href="www.myspace.com/themonads" target="_blank">The Monads</a> and end at midnight with <a href="www.myspace.com/somanydynamos" target="_blank">So Many Dynamos</a>.  Also it is the last <a href="www.myspace.com/victoriastl" target="_blank">Victoria</a> show.  So basically I don't really know what else you could be doing on a Saturday night. You can check out the schedule, <a href="http://blogs.riverfronttimes.com/atoz/2008/08/the_lot_schedule_saturday_august_23_metropolis_lineup_schlafly_tap_room.php" target="_blank">here</a> via A to Z.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Unstacking Monads for Performance]]></title>
<link>http://obfuscatedcode.wordpress.com/?p=49</link>
<pubDate>Sat, 17 May 2008 19:25:08 +0000</pubDate>
<dc:creator>dbueno</dc:creator>
<guid>http://obfuscatedcode.wordpress.com/?p=49</guid>
<description><![CDATA[While reflecting on how I might be able to improve my SAT solver, I discovered that my inner bottlen]]></description>
<content:encoded><![CDATA[<p>While reflecting on how I might be able to improve <a href="http://obfuscatedcode.wordpress.com/2008/04/18/a-modern-sat-solver-in-haskell/">my SAT solver</a>, I discovered that my <del datetime="00">inner</del> bottleneck loop contained two monad transformers (<a href="http://haskell.org/ghc/docs/latest/html/libraries/mtl/Control-Monad-Error.html#t%3AErrorT">ErrorT</a> and <a href="http://haskell.org/ghc/docs/latest/html/libraries/mtl/Control-Monad-State-Lazy.html#t%3AStateT">StateT</a>) on top of a base monad (<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Monad-ST.html">ST</a>).  The two transformers are provided by the <a href="http://hackage.haskell.org/cgi-bin/hackage-scripts/package/mtl">Monad Transformer Library</a> (MTL).  According to the <a href="http://haskell.org/haskellwiki/Performance/Monads">Haskell Wiki's page on improving performance with monads</a>:</p>
<blockquote><p>
MTL is an excellent library for programming with monads. However stacked monad transformers do not inline well and the library is in need of an optimization pass. As a result, it can often impose a performance hit of up to 300% (your code will run up to three times slower).</p></blockquote>
<p>Err ... I guess having stacked transformers is a <em>Bad Idea</em> for my inner loop.  So I set out to improve the situation.  On the same wiki page, there is <a href="http://r6.ca/blog/20071028T162529Z.html">a report</a> of excellent speedups for the continuation-passing-style (CPS) approach (section 2 on the wiki).  The idea is that you implement a custom monad manually combining the features you want, in CPS.</p>
<h2>The State-threading-ST-Error Monad</h2>
<p>Accordingly, following the advice of that same wiki page, I implemented a new monad supporting state threading, errors, and ST actions, all in continuation-passing style:</p>
<pre>
&#62; {-# LANGUAGE PolymorphicComponents
&#62;             ,MultiParamTypeClasses
&#62;             ,FunctionalDependencies
&#62;             ,FlexibleInstances
&#62;  #-}
&#62;
&#62; import Control.Monad.Error hiding ((&#62;=&#62;), forM_)
&#62; import Control.Monad.ST.Strict
&#62; import Control.Monad.State.Lazy hiding ((&#62;=&#62;), forM_)
&#62; import Control.Monad.MonadST
</pre>
<p>Performing an ST action requires a kind of lifting.</p>
<pre>
&#62; dpllST :: ST s a -&#62; SSTErrMonad e st s a
&#62; {-# INLINE dpllST #-}
&#62; dpllST st = SSTErrMonad (\k s -&#62; st &#62;&#62;= \x -&#62; k x s)
&#62;
</pre>
<p><code>SSTErrMonad e st s a</code>: the error type e, state type st, ST thread<br />
s and result type a.</p>
<pre>
&#62; newtype SSTErrMonad e st s a =
&#62;     SSTErrMonad { unSSTErrMonad :: forall r. (a -&#62; (st -&#62; ST s (Either e r, st)))
&#62;                               -&#62; (st -&#62; ST s (Either e r, st)) }
&#62;
&#62; instance Monad (SSTErrMonad e st s) where
&#62;     return x = SSTErrMonad ($ x)
&#62;     m &#62;&#62;= f  = bindSSTErrMonad m f
&#62;
&#62; bindSSTErrMonad :: SSTErrMonad e st s a -&#62; (a -&#62; SSTErrMonad e st s b) -&#62; SSTErrMonad e st s b
&#62; {-# INLINE bindSSTErrMonad #-}
&#62; bindSSTErrMonad m f = SSTErrMonad (\k -&#62; unSSTErrMonad m (\a -&#62; unSSTErrMonad (f a) k))
&#62;
&#62; instance MonadState st (SSTErrMonad e st s) where
&#62;     get = SSTErrMonad (\k s -&#62; k s s)
&#62;     put s' = SSTErrMonad (\k _ -&#62; k () s')
&#62;
&#62; instance (Error e) =&#62; MonadError e (SSTErrMonad e st s) where
&#62;     throwError err =            -- throw away continuation
&#62;         SSTErrMonad (\_ s -&#62; return (Left err, s))
&#62;     catchError action handler = SSTErrMonad
&#62;         (\k s -&#62; do (x, s')                      case x of
&#62;                       Left error -&#62; unSSTErrMonad (handler error) k s'
&#62;                       Right result -&#62; k result s')
</pre>
<p>The brilliant thing about this implementation is that the monadic bind operator <code>&#62;&#62;=</code> <em>does no case analysis</em>: only if you explicitly attempt to catch an error do you need to do case analysis.  In contrast, the <a href="http://haskell.org/ghc/docs/latest/html/libraries/mtl/src/Control-Monad-Error.html#ErrorT">ErrorT implementation</a> does:</p>
<pre>
instance (Monad m, Error e) =&#62; Monad (ErrorT e m) where
    m &#62;&#62;= k  = ErrorT $ do
        a &#60;- runErrorT m
        case a of
            Left  l -&#62; return (Left l)
            Right r -&#62; runErrorT (k r)
    ...
</pre>
<p>The wiki page argues essentially that function calling (in my monad's <code>&#62;&#62;=</code>) is less expensive than constant case analysis when errors are <em>uncommon</em>.  And indeed, in my solver, they are uncommon (outside the inner loop, they are not possible).</p>
<h2>Pretty Result Graphs; and, What did I do wrong?</h2>
<p>But the result is a letdown:<br />
<a href="http://obfuscatedcode.files.wordpress.com/2008/05/handcrafted-cps-monad-test1.png"><img src="http://obfuscatedcode.wordpress.com/files/2008/05/handcrafted-cps-monad-test1.png?w=300" alt="" width="300" height="225" class="alignnone size-medium wp-image-51" /></a><br />
(Graph produced using a <a href="http://hackage.haskell.org/cgi-bin/hackage-scripts/package/Chart">Haskell Chart</a> library, built on top of <a href="http://www.haskell.org/gtk2hs/">gtk2hs</a>.)</p>
<p>The graph compares the runtime (in seconds) of the original code, in blue, with the new code, in red, on 52 benchmarks available from <a href="http://www.satlib.org">SATLIB</a>.</p>
<p>The new monad only improves solving times slightly across my benchmarks.  So, possibilities:</p>
<ul>
<li>I've implemented the monad incorrectly, which doesn't seem likely since my many tests pass.</li>
<li>I've implemented the monad correctly but <em>inefficiently</em>.</li>
<li>The time spent doing case analysis isn't significant compared with function invocation.</li>
</ul>
<p>If anyone has a suggestion, please post it in the comments.  I'll definitely try it out.</p>
<h4>P.S. Rest of SSTErrMonad, if you're interested</h4>
<pre>
&#62; -- &#124; @runSSTErrMonad m s@ executes a `SSTErrMonad' action with initial state @s@
&#62; -- until an error occurs or a result is returned.
&#62; runSSTErrMonad :: (Error e) =&#62; SSTErrMonad e st s a -&#62; (st -&#62; ST s (Either e a, st))
&#62; runSSTErrMonad m = unSSTErrMonad m (\x s -&#62; return (return x, s))
&#62;
&#62; evalSSTErrMonad :: (Error e) =&#62; SSTErrMonad e st s a -&#62; st -&#62; ST s (Either e a)
&#62; evalSSTErrMonad m s = do (result, _)                           return result
</pre>
<p><strong>Update 17 May 2008, 1549</strong>: The graph was on too big a scale because of one point, so I removed the point and now the differences are more manifest.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Big, Muddy, and "Ornery"]]></title>
<link>http://hwy61.wordpress.com/?p=335</link>
<pubDate>Fri, 14 Mar 2008 20:08:40 +0000</pubDate>
<dc:creator>Matthew</dc:creator>
<guid>http://hwy61.wordpress.com/?p=335</guid>
<description><![CDATA[
The video above is a short trailer of the record release party for The Monads, who will release th]]></description>
<content:encoded><![CDATA[<p><span style='text-align:center; display: block;'><object width='425' height='350'><param name='movie' value='http://www.youtube.com/v/qwz5LcWD4KA'></param><param name='wmode' value='transparent'></param><embed src='http://www.youtube.com/v/qwz5LcWD4KA&rel=0' type='application/x-shockwave-flash' wmode='transparent' width='425' height='350'></embed></object></span></p>
<p>The video above is a short trailer of the record release party for <a href="http://www.myspace.com/themonads">The Monads</a>, who will release their second album "Ornery" on Big Muddy Records.  Watch it, I'll wait.  From the looks of the clip above, it would appear more bad news lies ahead of the primary calendar for Hillary Clinton (watch the video again if you need an explanation of that). </p>
<p>If "not even a robot Hillary Clinton" can stop this imminent release, you'll know you'll want to be at <a href="http://maps.google.com/maps?f=q&#38;hl=en&#38;geocode=&#38;q=Off+Broadway&#38;sll=38.655905,-90.304647&#38;sspn=0.006267,0.016587&#38;ie=UTF8&#38;ll=38.593193,-90.223975&#38;spn=0.012545,0.033174&#38;z=15&#38;iwloc=A">Off Broadway</a> on <a href="http://www.google.com/calendar/embed?src=hwy61revised%40gmail.com&#38;ctz=America/Chicago">March 28th around 9pm</a>.  But get there early, because the first 50 paying guests will receive a complimentary copy of the CD, and our friends at Big Muddy promise surprises:</p>
<blockquote><p>"Toenail clippings collected from everyone in the band is a possibility," said Monads' banjo player Jason Matthews. "Maybe even an essay I wrote on the proper way to tree a raccoon. You'll just have to find out for yourself!"</p></blockquote>
<p>To find that out you'll need to bring $7 and one of them picture identification cards to prove you're over the age of 18.  Getting age checked is just the start of your "Ornery" experience on March 28; alongside the bluegrass-styling of the Monads will be emceed by Clownvis Presley anchored by other Big Muddy favorites the Vultures and Pokey LaFarge.  Yep, see you there.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Don't fear the monads]]></title>
<link>http://dutherenverseauborddelatable.wordpress.com/?p=66</link>
<pubDate>Tue, 26 Feb 2008 18:33:58 +0000</pubDate>
<dc:creator>yoric</dc:creator>
<guid>http://dutherenverseauborddelatable.wordpress.com/?p=66</guid>
<description><![CDATA[If you are a developer keeping somewhat up-to-date with the latest and upcoming trends, chances are ]]></description>
<content:encoded><![CDATA[<p align="justify">If you are a developer keeping somewhat up-to-date with the latest and upcoming trends, chances are that you have heard of monads. Now, one of the traditions among developers who hear about monads is to figure them out then write a tutorial. I haven't quite reached the second stage, but I can point you to a <a href="http://channel9.msdn.com/Showpost.aspx?postid=358968">1h on-line video lecture</a>, targeted for C# and Java developers, and introducing both functional programming and monads.</p>
<p align="justify">Enjoy !</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[A Few Gig Posters from an Angry Preacher]]></title>
<link>http://viciousblog.wordpress.com/?p=21</link>
<pubDate>Sat, 09 Feb 2008 00:36:17 +0000</pubDate>
<dc:creator>viciousblog</dc:creator>
<guid>http://viciousblog.wordpress.com/?p=21</guid>
<description><![CDATA[
]]></description>
<content:encoded><![CDATA[<div style="text-align:center;"><img src="http://a239.ac-images.myspacecdn.com/images01/57/l_11e448ca209e7278af865de013773dbe.jpg" height="3400" width="424" /></div>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Exception Monad for OCaml]]></title>
<link>http://dutherenverseauborddelatable.wordpress.com/?p=56</link>
<pubDate>Thu, 31 Jan 2008 22:52:12 +0000</pubDate>
<dc:creator>yoric</dc:creator>
<guid>http://dutherenverseauborddelatable.wordpress.com/?p=56</guid>
<description><![CDATA[
I have just released a first version of a library introducing an exception monad in OCaml. More inf]]></description>
<content:encoded><![CDATA[<div class="snap_preview">
<p align="justify">I have just released a first version of a library introducing an exception monad in OCaml. More informations <a href="http://dutherenverseauborddelatable.wordpress.com/downloads/exception-monads-for-ocaml/">here</a>.</p>
<p align="justify">Je viens de publier la première version d'une bibliothèque introduisant les monades d'exceptions en OCaml. Plus d'informations <a href="http://dutherenverseauborddelatable.wordpress.com/downloads/exception-monads-for-ocaml/">ici</a>.</p>
</div>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Understanding monads]]></title>
<link>http://shreevatsa.wordpress.com/2008/01/04/understanding-monads/</link>
<pubDate>Fri, 04 Jan 2008 20:40:27 +0000</pubDate>
<dc:creator>Shreevatsa</dc:creator>
<guid>http://shreevatsa.wordpress.com/2008/01/04/understanding-monads/</guid>
<description><![CDATA[&#8220;Sigfpe&#8221; (Dan Piponi) has written some helpful posts on his blog. Together with other st]]></description>
<content:encoded><![CDATA[<p>"Sigfpe" (Dan Piponi) has written some helpful posts on his blog. Together with other stuff, I understand it... somewhat. Or maybe I understand it perfectly, I don't know.</p>
<p>Although they are in descending order of "simpleness", this is the order in which I saw them:<br />
First, read <a href="http://en.wikibooks.org/wiki/Haskell/Understanding_monads">the definition of monads from here</a> (only), and stop. It probably won't make sense.</p>
<p>This excellent post:<br />
<a href="http://sigfpe.blogspot.com/2006/08/you-could-have-invented-monads-and.html">You Could Have Invented Monads! (And Maybe You Already Have.)</a><br />
explains monads with enough examples -- they are a kind of "lift". The definition makes sense now.</p>
<p>That, and <a href="http://citeseer.ist.psu.edu/wadler95monads.html">Philip Wadler's original paper</a> should suffice.</p>
<p>There are <a href="http://www.haskell.org/haskellwiki/Monad_tutorials_timeline">too many monad tutorials</a>, and quoting from <a href="http://unenterprise.blogspot.com/2008/02/tell-us-why-your-language-sucks.html">Tell us why your language sucks</a>:</p>
<blockquote><p>
So, things I hate about Haskell:</p>
<p>Let's start with the obvious. Monad tutorials. No, not monads. Specifically the tutorials. They're endless, overblown and dear god are they tedious. Further, I've never seen any convincing evidence that they actually help. Read the class definition, write some code, get over the scary name. </p></blockquote>
<hr />
<p>[Random interesting stuff:<br />
This post looks at them as "expressions" v/s "commands":<br />
<a href="http://sigfpe.blogspot.com/2007/11/io-monad-for-people-who-simply-dont.html">The IO Monad for People who Simply Don't Care</a></p>
<p>There's also some interesting stuff in the first half of <a href="http://sigfpe.blogspot.com/2007/06/monads-from-algebra-and-the-gray-code.html">this post</a>.]</p>
<p><a href="http://www.loria.fr/~kow/monads/index.html">Of monads and spacesuits</a> is the famous tutorial that uses <em>spaceships and astronauts</em> to illustrate monads ("spacesuits"), which I thought was clearly overkill, but reading it, it is actually pretty good. But again, I'm unconvinced it would actually help anyone understand monads -- it is only useful after you have been using monads for a while.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Monads! (and Why Monad Tutorials Are All Awful)]]></title>
<link>http://ahamsandwich.wordpress.com/2007/07/26/monads-and-why-monad-tutorials-are-all-awful/</link>
<pubDate>Thu, 26 Jul 2007 06:54:00 +0000</pubDate>
<dc:creator>csgordon</dc:creator>
<guid>http://ahamsandwich.wordpress.com/2007/07/26/monads-and-why-monad-tutorials-are-all-awful/</guid>
<description><![CDATA[If you have an affinity for programming language theory (as I do), and wander around the internet se]]></description>
<content:encoded><![CDATA[<p>If you have an affinity for <a href="http://en.wikipedia.org/wiki/Programming_language_theory">programming language theory</a> (as I do), and wander around the internet searching for topics of interest, eventually you <i>will</i> run into references to monads.  They're neither trivial, nor as complex as the dearth of proper explanations of them might suggest.</p>
<p>In a nutshell, they are the PLT manifestation of a concept from <a href="http://en.wikipedia.org/wiki/Category_theory">category theory</a>, and abstract away propagation of results and side effects, without actually performing side effects or leaving a pure-functional paradigm.  Any attempt at description beyond that point tends to either
<ul>
<li>a) get terribly botched*, or</li>
<li>b) turn into a real category theory explanation, which most people don't have the background to understand easily</li>
</ul>
<p>and for those reasons I will refrain from attempting further explanation myself.  I don't have confidence in my own ability to explain in a non-interactive medium, and I certainly don't have the mathematics background to formalize it.</p>
<p>The internet is littered with tutorials and explanations "in laymen's terms" of what monads are, what they are for, why we care, etc.  Every such tutorial I have started (at least a dozen, probably several more - all highly recommended) has either bored me to tears, struck me as completely inane, or simply confused me.</p>
<p>I had decided that I was simply going to have to learn abstract algebra and category theory in order to really get a handle on what they were, until a wonderful post appeared on <a href="http://lambda-the-ultimate.org/">LtU</a>, linking to one of the earlier papers on monads.  The paper, by Philip Wadler, gives not only a clear explanation of what a monad is, but also provides a strong motivation for looking for monads, an approachable description of how they are derived from a practical point of view for use in a type system, and a number of <i>useful</i>, <i>nontrivial</i> examples.  Probably one of the most well-written academic papers I've read.  You should be familiar with an ML-style type system and notation to understand the examples.  Or you need be be good at picking up such things on the fly.</p>
<p><a href="http://citeseer.ist.psu.edu/wadler95monads.html">Monads for Functional Programming</a>.  Enjoy.</p>
<hr />* The canonical example of a monad is for some reason the Maybe monad, though I don't know why - it's certainly a monad, but it's actually not the most intuitive first example.  Most of the monad explanations I found online immediately launch into using Maybe as an example of why monads aren't hard.  They're not, but the example is usually provided far too early, without enough background, motivation, or explanation, making the reader simply feel like he or she is missing some greater complexity (which is true) which was already explained (which usually is not the case).  Wadler's example of a simple interpreter is much clearer.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Logic of Sense: Series 25]]></title>
<link>http://fractalontology.wordpress.com/2007/04/04/logic-of-sense-series-25/</link>
<pubDate>Wed, 04 Apr 2007 02:07:00 +0000</pubDate>
<dc:creator>Taylor Adkins</dc:creator>
<guid>http://fractalontology.wordpress.com/2007/04/04/logic-of-sense-series-25/</guid>
<description><![CDATA[Of course, with Series 25, one could, along with Badiou, single out the title as the concept that ne]]></description>
<content:encoded><![CDATA[<p class="MsoNormal">Of course, with Series 25, one could, along with Badiou, single out the title as the concept that needs to be unpacked, especially since univocity has a particularly Deleuzian ring to it.<span>  </span>But the term—and Deleuze starts using it around p. 150 in the text—that most interests me in this series is <em>counter-actualization</em>.<span>  </span></p>
<p class="MsoNormal"><span>            </span>On the one hand, we can remember the play of the virtual/actual couple that Badiou finds so fun to dismantle. On the other, the most important thing is to signify how this term works in this particularly situated part of the text.<span>  </span>So, giving Deleuze the benefit of the doubt, we should keep in mind that Deleuze doesn’t use the word <em>virtual</em> anywhere in this passage.<span>  </span>Neither does he use the word <em>compossible</em> in this passage, but since he has introduced this term with reference to Leibniz, I think it’s important to stress a point that Deleuze makes at the beginning of the series: there is no such thing as incompatibility between events because such a term can only be used when referring to worlds, individuals, or persons (177).<span>  </span>Since the disjunctive synthesis is the basis for the affirmation of the divergent, worlds that actualize events can become incompatible because of the divergent singularities that populate their series; strictly speaking though, “it seems that all events, even contraries, are compatible” (177).<span>  </span></p>
<p class="MsoNormal"><span>            </span>So, simply put, Deleuze’s question is: how is the individual able to “transcend his form and his syntactical link with a world” in order to “attain the universal communication of events” (178).<span>  </span>But this is not so simple.<span>  </span>Here Deleuze seems to mean the following: if, as quoted above, all events are compatible, then how is any language of the event possible?<span>  </span>Before following Deleuze’s argument more closely, we should bring Leibniz back to the center of discussion.<span>  </span>Deleuze draws on and explicates Leibniz’s theory of monads through <em>The Logic of Sense</em>, and so it would not be inappropriate here to talk about his theory of monads: all monads “perceive” the world from a distinct perspective and also link up with other monads, causing permutations in the vicinity as they link up--Deleuze continues this discussion in <em>Difference and Repetition</em> in order to explain the ways in which the monads express a differential relation between themselves (47).<span>  </span>So, in themselves, monads contain a grain of truth about the world which they inhabit.<span>  </span>Each monad must be considered in itself, a part which has a reciprocal relationship with other parts, like a link in a signifying chain, and thus a world is constructed from this double action.<span>  </span></p>
<p class="MsoNormal"><span>            </span>Yet, as Deleuze points out, with the event we cannot refer to a grammar of worlds.<span>  </span>Syntactically, the event seems both to insist on its <em>extra-being</em> and also entail a pre-individuality that lacks any true communicability.<span>  </span>That’s unless we can bring about counter-actualization.<span>  </span>In the sense that I understand it, counter-actualization comes about when an individual considers herself as an event and that event as “another individual grafted onto her” (178).<span>  </span>This double affirmation extends to treating other individuals as events and their events as individuals—it is this affirmation that brings events “to the power of the eternal return” (178).<span>  </span>The power of the eternal return is what allows for an affirmation of the disjunctive synthesis; in other words, the divergence of two series (individuals with respect to the distance of other individuals/events) is not only affirmative <em>but it necessarily alters the other series by resonating in it and vice versa</em>.<span>  </span>It is the conjunction of Leibnizian monads and counter-actualization that allows for Deleuze to talk of a unique Event.<span>  </span>It is this unique Event that the univocity of Being is: “if Being is the unique event in which all events communicate with one another, univocity refers both to what occurs and to what is said” (180).<span>  </span></p>
<p class="blogger-post-footer">--Taylor Adkins</p>
<p class="blogger-post-footer">(c) Fractal Ontology, 2007</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Monads, Vector Spaces and Quantum Mechanics pt. II]]></title>
<link>http://sigfpe.wordpress.com/2007/03/04/monads-vector-spaces-and-quantum-mechanics-pt-ii/</link>
<pubDate>Sun, 04 Mar 2007 20:43:22 +0000</pubDate>
<dc:creator>sigfpe</dc:creator>
<guid>http://sigfpe.wordpress.com/2007/03/04/monads-vector-spaces-and-quantum-mechanics-pt-ii/</guid>
<description><![CDATA[I had originally intended to write some code to simulate quantum computers and implement some quantu]]></description>
<content:encoded><![CDATA[<p>I had originally intended to write some code to simulate quantum computers and implement some quantum algorithms. I'll probably eventually do that but today I just want to look at quantum mechanics in its own right as a kind of generalisation of probability. This is probably going to be the most incomprehensible post I've written in this blog. On the other hand, even though I eventually talk about the philosophy of quantum mechanics, there's some Haskell code to play with at every stage, and the codeives the same results as appear in physics papers, so maybe that will help give a handle on what I'm saying.</p>
<p>First get some Haskell fluff out of the way:</p>
<pre>
&#62; import Prelude hiding (repeat)
&#62; import Data.Map (toList,fromListWith)
&#62; import Complex
&#62; infixl 7 .*
</pre>
<p>Now define certain types of vector spaces. The idea is the a <code>W b a</code> is a vector in a space whose basis elements are labelled by objects of type <code>a</code> and where the coefficients are of type <code>p</code>.</p>
<pre>
&#62; data W b a = W { runW :: [(a,b)] } deriving (Eq,Show,Ord)
</pre>
<p>This is very similar to standard probability monads except that I've allowed the probabilities to be types other than <code>Float</code>. Now we need a couple of ways to operate on these vectors.</p>
<p><code>mapW</code> allows the application of a function transforming the probabilities...</p>
<pre>
&#62; mapW f (W l) = W $ map (\(a,b) -&#62; (a,f b)) l
</pre>
<p>and <code>fmap</code> applies a function to the basis element labels.</p>
<pre>
&#62; instance Functor (W b) where

&#62;    fmap f (W a) = W $ map (\(a,p) -&#62; (f a,p)) a
</pre>
<p>We want our vectors to support addition, multiplication, and actually form a monad. The definition of <code>&#62;&#62;=</code> is similar to that for other probability monads. Note how vector addition just concatenates our lists of probabilities. The problem with this is that if we have a vector like $latex a+2a$ we'd like it to be reduced to $latex 3a$ but in order to do that we need to be able to spot that the two terms $latex a$ and $latex 2a$ both contain multiples of the same vector, and to do that we need the fact that the labels are instances of <code>Eq</code>. Unfortunately we can't do this conveniently in Haskell because of the lack of <a href="http://citeseer.ist.psu.edu/hughes99restricted.html">restricted datatypes</a> and so to collect similar terms we need to use a separate <code>collect</code> function:</p>
<pre>
&#62; instance Num b =&#62; Monad (W b) where
&#62;    return x = W [(x,1)]
&#62;    l &#62;&#62;= f = W $ concatMap (\(W d,p) -&#62; map (\(x,q)-&#62;(x,p*q)) d) (runW $ fmap f l)

&#62; a .* b = mapW (a*) b

&#62; instance (Eq a,Show a,Num b) =&#62; Num (W b a) where
&#62;     W a + W b = W $ (a ++ b)
&#62;     a - b = a + (-1) .* b
&#62;     _ * _ = error "Num is annoying"
&#62;     abs _ = error "Num is annoying"
&#62;     signum _ = error "Num is annoying"
&#62;     fromInteger a = if a==0 then W [] else error "fromInteger can only take zero argument"

&#62; collect :: (Ord a,Num b) =&#62; W b a -&#62; W b a

&#62; collect = W . toList . fromListWith (+) . runW
</pre>
<p>Now we can specialise to the two monads that interest us:</p>
<pre>
&#62; type P a = W Float a

&#62; type Q a = W (Complex Float) a
</pre>
<p><code>P</code> is the (hopefully familiar if you've read Eric's recent posts) probability monad. But <code>Q</code> allows complex probabilities. This is because quantum mechanics is a lot like probability theory with complex numbers and many of the rules of probability theory carry over.</p>
<p>Suppose we have a (non-quantum macroscopic) coin that we toss. It's state might be described by:</p>
<pre>
&#62; data Coin = Heads &#124; Tails deriving (Eq,Show,Ord)

&#62; coin1 = 0.5 .* return Heads + 0.5 .* return Tails :: P Coin
</pre>
<p>Suppose that if Albert sees a coin that is heads up he has a 50% chance of turning it over and if he sees a coin that is tails up he has a 25% chance of turning it over. We can describe Albert like this:</p>
<pre>
&#62; albert Heads = 0.5 .* return Heads + 0.5 .* return Tails
&#62; albert Tails = 0.25 .* return Heads + 0.75 .* return Tails
</pre>
<p>We can now ask what happens if Albert sees a coin originally turned up heads n times in a row:</p>
<pre>
&#62; repeat 0 f = id
&#62; repeat n f = repeat (n-1) f . f&#62; (-&#62;-) :: a -&#62; (a -&#62; b) -&#62; b

&#62; g -&#62;- f = f g

&#62; (-&#62;&#60;) :: Q a -&#62; (a -&#62; Q b) -&#62; Q b
&#62; g -&#62;&#60; f = g &#62;&#62;= f

&#62; albert1 n = return Heads -&#62;- repeat n (-&#62;&#60; albert) -&#62;- collect
</pre>
<p>Let me explain those new operators. <code>-&#62;-</code> is just function application written from left to right. The <code>&#62;</code> in the middle is intended to suggest the direction of data flow. <code>-&#62;&#60;</code> is just <code>&#62;&#62;=</code> but I've written it this way with the final <code>&#60;</code> intended to suggest the way a function <code>a -&#62; M b</code> 'fans out'. Anyway, apropos of nothing else, notice how Albert approaches a steady state as n gets larger.</p>
<p>Quantum mechanics works similarly but with the following twist. When we come to observe the state of a quantum system it undergoes the following radical change:</p>
<pre>
&#62; observe :: Ord a =&#62; Q a -&#62; P a

&#62; observe = W . map (\(a,w) -&#62; (a,magnitude (w*w))) . runW . collect
</pre>
<p>Ie. the quantum state becomes an ordinary probabilistic one. This is called <a href="http://en.wikipedia.org/wiki/Wavefunction_collapse">wavefunction collapse</a>. Before collapse, the complex weights are called 'amplitudes' rather than probabilities. The business of physicists is largely about determining what these amplitudes are. For example, the well known <a href="http://en.wikipedia.org/wiki/Schrödinger%27s_equation">Schrödinger equations</a> is a lot like a kind of probabilistic diffusion, like a random walk, except with complex probabilities instead of amplitudes. (That's why so many physicists have been hired into finance firms in recent years - stocks follow a random walk which has formal similarities to quantum physics.)</p>
<p>The rules of quantum mechanics are a bit like those of probability theory. In probability theory the sum of the probabilites must add to one. In addition, any process (like <code>albert</code>) must act in such a way that if the input sum of probabilities is one, then so is the output. This means that probabilistic process are <a href="http://en.wikipedia.org/wiki/Stochastic_matrix">stochastic</a>. In quantum mechanics the sum of the squares of the magnitudes of the amplitudes must be one. Such a state is called 'normalised'. All processes must be such that normalised inputs go to normalised outputs. Such processes are called <a href="http://en.wikipedia.org/wiki/Unitary_matrix">unitary</a> ones.</p>
<p>There's a curious subtlety present in quantum mechanics. In classical probability theory you need to have the sum of the probabilities of your different events to sum to one. But it's no good having events like "die turns up 1", "die turns up 2", "die turns up even" at the same time. "die turns up even" includes "die turns up 2". So you always need to work with a mutually exclusive set of events. In quantum mechanics it can be pretty tricky to figure out what the mutually exclusive events are. For example, when considering the spin of an electron, there are no more mutually exclusive events beyond "spin up" and "spin down". You might think "what about spin left?". That's just a mixture of spin up and spin down - and that fact is highly non-trivial and non-obvious. But I don't want to discuss that now and it won't affect the kinds of things I'm considering below.</p>
<p>So here's an example of a quantum process a bit like <code>albert</code> above. For any angle $latex \theta$, <code>rotate</code> turns a boolean state into a mixture of boolean states. For $latex \theta=0$ it just leaves the state unchanged and for $latex \theta=\pi$ it inverts the state so it corresponds to the function <code>Not</code>. But for $latex \theta=\pi/2$ it does something really neat: it is a kind of square root of <code>Not</code>. Let's see it in action:</p>
<pre>
&#62; rotate :: Float -&#62; Bool -&#62; Q Bool
&#62; rotate theta True = let theta' = theta :+ 0
&#62;   in cos (theta'/2) .* return True - sin (theta'/2) .* return False

&#62; rotate theta False = let theta' = theta :+ 0
&#62;   in cos (theta'/2) .* return False + sin (theta'/2) .* return True

&#62; snot = rotate (pi/2)

&#62; repeatM n f = repeat n (&#62;&#62;= f)

&#62; snot1 n = return True -&#62;- repeatM n snot -&#62;- observe
</pre>
<p>We can test it by running <code>snot1 2</code> to see that two applications take you to where you started but that <code>snot1 1</code> gives you a 50/50 chance of finding <code>True</code> or <code>False</code>. Nothing like this is possible with classical probability theory and it can only happen because complex numbers can 'cancel each other out'. This is what is known as 'destructive interference'. In classical probability theory you only get constructive interference because probabilities are always positive real numbers. (Note that <code>repeatM</code> is just a monadic version of repeat - we could have used it to simplify <code>albert1</code> above so there's nothing specifically quantum about it.)</p>
<p>Now for two more combinators:</p>
<pre>
&#62; (=&#62;=) :: P a -&#62; (a -&#62; b) -&#62; P b
&#62; g =&#62;= f = fmap f g&#62; (=&#62;&#60;) :: P (Q a) -&#62; (a -&#62; Q b) -&#62; P (Q b)
&#62; g =&#62;&#60; f = fmap (&#62;&#62;= f) g
</pre>
<p>The first just uses <code>fmap</code> to apply the function. I'm using the <code>=</code> sign as a convention that the function is to be applied not at the top level but one level down within the datastructure. The second is simply a monadic version of the first. The reason we need the latter is that we're going to have systems that have both kinds of uncertainty - classical probabilistic uncertainty as well as quantum uncertainty. We'll also want to use the fact that <code>P</code> is a monad to convert doubly uncertain events to singly uncertain ones. That's what <code>join</code> does:</p>
<pre>
&#62; join :: P (P a) -&#62; P a
&#62; join = (&#62;&#62;= id)
</pre>
<p>OK, that's enough ground work. Let's investigate a physical process that can be studied in the lab: the <a href="http://en.wikipedia.org/wiki/Quantum_Zeno_effect">Quantum Zeno effect</a>, otherwise known as the fact that a watched pot never boils. First an example related to <code>snot1</code>:</p>
<pre>
&#62; zeno1 n = return True -&#62;- repeatM n (rotate (pi/fromInteger n)) -&#62;- collect -&#62;- observe
</pre>
<p>The idea is that we 'rotate' our system through an angle $latex \pi/n$ but we do so in n stages. The fact that we do it in n stages makes no difference, we get the same result as doing it in one go. The slight complication is this: suppose we start with a probabilistic state of type <code>P a</code>. If we let it evolve quantum mechanically it'll turn into something of type <code>P (Q a)</code>. On observation we get something of type <code>P (P a)</code>. We need <code>join</code> to get a single probability distribution of type <code>P a</code>. The <code>join</code> is nothing mysterious, it just combines the outcome of two successive probabilistic processes into one using the usual laws of probability.</p>
<p>But here's a variation on that theme. Now we carry out n stages, but after each one we observe the system causing wavefunction collapse:</p>
<pre>
&#62; zeno2 n = return True -&#62;- repeat n (
&#62;     \x -&#62; x =&#62;= return =&#62;&#60; rotate (pi/fromInteger n) =&#62;= observe -&#62;- join
&#62;     ) -&#62;- collect
</pre>
<p>Notice what happens. In the former case we flipped the polarity of the input. In this case it remains closer to the original state. The higher we make n the closer it stays to its original state. (Not too high, start with small n. The code suffers from combinatorial explosion.) <a href="http://www.boulder.nist.gov/timefreq/general/pdf/858.pdf">Here</a>'s a paper describing the actual experiment. Who needs all that messing about with sensitive equipment when you have a computer? :-)</p>
<p>A state of the form <code>P (Q a)</code> is called a mixed state. Mixed states can get a bit hairy to deal with as you have this double level of uncertainty. It can get even trickier because you can sometimes observe just <em>part</em> of a quantum system rather than the whole system like <code>oberve</code> does.  This inevitably leads mixed states. von Neumann came up with the notion of a <a href="http://en.wikipedia.org/wiki/Density_matrix">density matrix</a> to deal with this, although a <code>P (Q a)</code> works fine too. I also have a hunch there is an elegant way to handle them through an object of type <code>P (Q (Q a))</code> that will eliminate the whole magnitude squared thing. However, I want to look at the quantum Zeno effect in another way that ultimately allows you deal with mixed states in another way. Unfortunately I don't have time to explain this elimination today, but we can look at the general approach.</p>
<p>In this version I'm going to consider a quantum system that consists of the logical state in the Zeno examples, but also include the state of the observer. Now standard <a href="http://en.wikipedia.org/wiki/Copenhagen_interpretation">dogma</a> says you can't can't form quantum states out of observers. In other words, you can't form <code>Q Observer</code> where <code>Observer</code> is the state of the observer. It says you can only form <code>P Observer</code>. Whatever. I'm going to represent an experimenter using a list that representing the sequence of measurements they have made. Represent the complete system by a pair of type <code>([Bool],Bool)</code>. The first element of the pair is the experimenter's memory and the second element is the state of the boolean variable being studied. When our experimenter makes a measurement of the boolean variable, its value is simply prepended to his or her memory:</p>
<pre>
&#62; zeno3 n = return ([],True) -&#62;- repeatM n (
&#62;    \(m,s) -&#62; do
&#62;     s' &#60;- rotate (pi/fromInteger n) s
&#62;     return (s:m,s')
&#62;    ) -&#62;- observe =&#62;= snd -&#62;- collect
</pre>
<p>Note how we now delay the final observation until the end when we observe both the experimenter and the poor boolean being experimented on. We want to know the probabilities for the final boolean state so we apply <code>snd</code> so as to discard the state of the observer's memory. Note how we get the same result as <code>zeno2</code>. (Note no mixed state, just an expanded quantum state that collapses to a classical probabilistic state.)</p>
<p>There's an interesting philosophical implication in this. If we model the environment (in this case the experimenter is part of that environment) as part of a quantum system, we don't need all the intermediate wavefunction collapses, just the final one at the end. So are the intermediate collapses real or not? The interaction with the environment is known as <a href="http://en.wikipedia.org/wiki/Decoherence">decoherence</a> and some hope that wavefunction collapse can be explained away in terms of it.</p>
<p>Anyway, time for you to go and do something down-to-earth like gardening. Me, I'm washing the kitchen floor...</p>
<hr />
I must mention an important cheat I made above. When I model the experimenter's memory as a list I'm copying the state of the measured experiment into a list. But you can't simply copy data into a quantum register. One way to see this is that unitary processes are always invertible. Copy data into a register destroys the value that was there before and hence is not invertible. So instead, imagine that we really have an array that starts out zeroed out and that each time something is added to the list, the new result is xored into the next slot in the array. The list is just non-unitary looking, but convenient, shorthand for this unitary process.</p>
<hr />
PS I'm not convinced this LateX stuff is working. If something doesn't make sense, looking around for equations that might have floated away :-) PPS wordpress teething troubles! I see that despite LaTeX support, wordpress is even more annoying than blogger in its handling of less than and greater than. It actually discards your HTML source sometimes. I've fixed one bit of discarded text. Additionally it also seems to discard backslash for no good reason. If you see something of the form a -&#62; b it probably ought to be "backslash" a -&#62; b. Apart from that, the code seems to work when copied and pasted from the blog into ghc.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Monads in C pt. III]]></title>
<link>http://sigfpe.wordpress.com/2007/03/03/monads-in-c-pt-iii/</link>
<pubDate>Sat, 03 Mar 2007 16:07:52 +0000</pubDate>
<dc:creator>sigfpe</dc:creator>
<guid>http://sigfpe.wordpress.com/2007/03/03/monads-in-c-pt-iii/</guid>
<description><![CDATA[OK, the last C monad example:

typedef struct {
  char *string;
  int value;
} WriterInt;

WriterInt]]></description>
<content:encoded><![CDATA[<p>OK, the last C monad example:</p>
<pre>
typedef struct {
  char *string;
  int value;
} WriterInt;

WriterInt returnWriter(int i)
{
  WriterInt r;
  r.string = "";
  r.value = i;
  return r;
}

WriterInt bind(WriterInt (*f)(int),WriterInt x)
{
  WriterInt y = f(x.value);
  WriterInt z;
  z.value = y.value;
  int len = strlen(x.string)+strlen(y.string);
  z.string = malloc(len+1);
  strcpy(z.string,x.string);
  strcat(z.string,y.string);
  return z;
}

WriterInt print(int i)
{
  WriterInt x;
  x.string = malloc(32);
  x.value = sprintf(x.string,"%d\n",i);
  return x;
}

WriterInt printplus_bad(int i)
{
  WriterInt x = print(i);
  return print(x.value); /* cheating! */
}

WriterInt printplus(int i)
{
  WriterInt x = print(i);
  return bind(print,x);
}
</pre>
<p>This time, instead of printing, we build up a string as a side effect. <code>printplus()</code> is implemented exactly as before, without knowledge of how to handle side effects, and yet it correctly handles strings returned as a side effect and concatenates them together. The magic is <code>bind()</code> which allows a function expecting an <code>int</code> input to be applied to a <code>WriterInt</code>.</p>
<p>I'm hoping that programmers of languages such as C can now begin to see the pattern shared by these examples.</p>
<p>Anyway, this is all just stalling for time while I try to get my quantum computation code working.</p>
]]></content:encoded>
</item>

</channel>
</rss>
