<?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>functional-programming &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://wordpress.com/tag/functional-programming/</link>
	<description>Feed of posts on WordPress.com tagged "functional-programming"</description>
	<pubDate>Sat, 26 Jul 2008 04:46:22 +0000</pubDate>

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

<item>
<title><![CDATA[Death of the Thread Model]]></title>
<link>http://moffdub.wordpress.com/?p=49</link>
<pubDate>Sat, 19 Jul 2008 20:21:37 +0000</pubDate>
<dc:creator>moffdub</dc:creator>
<guid>http://moffdub.wordpress.com/?p=49</guid>
<description><![CDATA[You haven&#8217;t really had the fear of Turing struck into you until you&#8217;ve tried concurrent ]]></description>
<content:encoded><![CDATA[<p>You haven't really had the fear of Turing struck into you until you've tried concurrent programming. Any lofty visions you've had of a normal, happy life as a programmer won't survive your first <a href="http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html">pthread </a>or <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Thread.html#run()">Thread.run()</a> call.</p>
<p>My most recent non-trivial attempt at threads was way back when in college. The course was "TCP/IP Programming." It was the kind of course that didn't interest me just from its title and description. Really, I signed up for it because the best professor in the entire school was delivering it, <a href="http://guinness.cs.stevens-tech.edu/~djd/">Dan Duchamp</a>, and this was my last semester. In the end, it actually wound up being an informative course, because networking is not my strong point.</p>
<p>We were warned that the assignments would be in C and would be back-breakers. This almost turned out to be true. I had Duchamp in three other courses, and sometimes he would overstate the scope of a project.</p>
<p>Our projects were:</p>
<ul>
<li>a <a href="http://en.wikipedia.org/wiki/Domain_Name_System">DNS</a> resolver that sent <a href="http://en.wikipedia.org/wiki/User_Datagram_Protocol">UDP</a> to DNS and relayed the result via <a href="http://en.wikipedia.org/wiki/Transmission_Control_Protocol">TCP</a> back to whomever requested it
<li>a simulation of <a href="http://en.wikipedia.org/wiki/Internet_Control_Message_Protocol">ICMP</a> and <a href="http://en.wikipedia.org/wiki/Internet_Protocol">IP</a>; this is one of the courses that I look back on and think "I can't believe I pulled that off"
<li>a link-state and distance vector routing simulation
<li>a simulation of TCP
<li>port the first assignment to the TCP simulation
</ul>
<p>Somehow, someway, I had no problem with the first three. Then I read the description of the TCP simulation, and I shuddered when I saw that three threads were required.</p>
<p>I pretty much knew right then that it was over.</p>
<p>In fact, after getting extra help from Duchamp, it became apparent that I needed to use <a href="https://computing.llnl.gov/tutorials/pthreads/man/pthread_cond_wait.txt">pthread_cond_wait</a>, <a href="https://computing.llnl.gov/tutorials/pthreads/man/pthread_cond_wait.txt">pthread_cond_timedwait</a>, <a href="https://computing.llnl.gov/tutorials/pthreads/#MutexCreation">pthread_mutex_t</a>, and <a href="https://computing.llnl.gov/tutorials/pthreads/man/pthread_cond_signal.txt">pthread_cond_signal</a> to name a few. These were system calls and types that I had never used before.</p>
<p>Duchamp, bless his heart, claimed that he covered them in the OS course, which I also took with him. While he covered <a href="http://www.cs.umd.edu/~shankar/412-Notes/10-BinarySemaphores.html">mutexes</a> and locking, we did not make use of <a href="http://www.cs.mtu.edu/~shene/NSF-3/e-Book/MONITOR/CV.html">condition variables</a> in assignments. So on top of the intellectual burden of dealing with my half-finished attempt at multi-threading, which was already based on a bad thread design (and it was too late to start over), I had to learn and use new system calls correctly.</p>
<p>My point is my last semester of senior year could've been much less stressful if programming with threads wasn't a death trap. At work, I asked our technical lead if they made use of multi-threading in the code, and the answer was a resounding "No, it becomes too ugly too quickly."</p>
<p>What's odd is that in most <a href="http://en.wikipedia.org/wiki/Create,_read,_update_and_delete">CRUD</a> apps, concurrency is transparent and under the hood. Most RDBM systems give you this for free in the form of <a href="http://en.wikipedia.org/wiki/Transaction_processing">transactional processing</a>.</p>
<p>So something can't be right. It can't be such a nightmare to do something like three threads, one for each layer boundary, plus another to do the real work, but so effortlessly achieve concurrent data access and processing. Why do I have to suffer through concurrency if it is not DB-related?</p>
<p>Then, once upon a time, I was listening to <a href="http://www.dotnetrocks.com">Dot Net Rocks</a> <a href="http://www.dotnetrocks.com/default.aspx?showNum=269">show #269</a>. The guest was <a href="http://www.knowing.net/">Larry O'Brien</a>, who was arguing that the thread-and-lock model is garbage:</p>
<blockquote><p>
<strong>Larry O'Brien</strong>: Oh, absolutely, but even if you get it and even if you think it's fun, there's a thing about that thread and process model that we have in the <a href="http://en.wikipedia.org/wiki/Common_Language_Runtime">CLR</a> today, which I would argue makes it <strong>fundamentally broken</strong> for business programming. So, check out this scenario. You have a library and it has some publicly available method by which it acquires a lock, right? </p>
<p><strong><a href="http://www.franklins.net/">Carl Franklin</a></strong>: Yeah.</p>
<p><strong>Larry O'Brien</strong>: And holds that lock and returns to you and you go about and do your other thing. If you have another method that calls that library on which that library performs a callback and by a callback I mean all sorts of important things. I'm talking about virtual method calls in a world of object orientation. I'm talking about delegates and events central to graphics programming and I'm talking about <a href="http://msdn.microsoft.com/en-us/library/bb397687.aspx">lambda expressions</a>, which are coming out in C# 3.0 and they're very important for <a href="http://en.wikipedia.org/wiki/LINQ">LINQ</a>. You can never safely have a library that simultaneously has a publicly triggerable lock that executes a callback to client code because it's perfectly legal for the client code to start up a new thread... </p>
<p><strong>Carl Franklin</strong>: Yeah. </p>
<p><strong>Larry O'Brien</strong>: And within that new thread, call that method attempts to get the lock which is already held by the previous thread and <strong>the end result of that is deadlock</strong>.
</p></blockquote>
<p>I'd take this even a step further: <strong>the thread-and-lock model of concurrency is broken because it is too low-level</strong>. Why, in this age of garbage collection, managed code, and workflow engines, hasn't the abstraction level been raised on concurrency as well?</p>
<p>The itching issue that needs scratching is that it has been for quite some time, but only in the niche of databases. Memory management used to be a pest; now there is platform support for garbage collection. We need similar support for concurrency. It was just then that the guys on the show discuss <a href="http://en.wikipedia.org/wiki/Software_transactional_memory">Software Transactional Memory</a>:</p>
<blockquote><p>
<strong>Larry O'Brien</strong>: Okay. Software Transactional Memory is essentially optimistic locking for memory.</p>
<p><strong>Carl Franklin</strong>: Yeah.</p>
<p><strong>Larry O'Brien</strong>: You wrap a call or a block in what's essentially a transaction. You say "Atomic, start block" and then you finish the block and it runs at full speed and then you have a follow-along processor that goes through it and it looks for that one in a thousand, one in a million memory collision. If a memory collision has occurred, it retries it. </p>
<p><strong>Carl Franklin</strong>: Yeah.</p>
<p><strong>Larry O'Brien</strong>: Yeah. It's not at all a bad model.
</p></blockquote>
<p>This would be a giant step forward. It does have its problems, namely that it still requires the programmer to be aware and predict what blocks of code are <a href="http://c2.com/cgi/wiki?CriticalSection">critical sections</a> in order to mark them off as transactions.</p>
<p>To take it a step higher, using <a href="http://en.wikipedia.org/wiki/Futures_and_promises">Futures</a>, this sort of demarcation can be delegated to the compiler and/or runtime environment entirely:</p>
<blockquote><p>
<strong>Larry O'Brien</strong>: Instead of trying to second guess the creation of thread, what you do is you say, "Well, I want this value" you know this value being returned from a function, "but I can either have the value or I can have" what Sutter calls "a Future." </p>
<p>A Future is basically an IOU. Okay, so you have this reference to a Future and when you need it, when you say, "Okay, I want to cash in this IOU" at that point, the system will block and guarantee that the value becomes concrete. So, just by sort of flipping things around from "Okay, let's create processes and kind of second guess how many cores I have" and those sorts of approaches.</p>
<p>This approach says, okay by simply having a whole bunch of IOUs floating around then it becomes possible for the compiler on the runtime to do a lot of really clever reasoning about "Oh hey, look. Here's this IOU, but I know that this IOU won't be required for several hundred milliseconds and so, therefore, I have enough information to distribute that to another <a href="http://en.wikipedia.org/wiki/Semiconductor_intellectual_property_core">core</a>."
</p></blockquote>
<p>The only drawback here is again another programmer-dependent pitfall. Functions that return Futures work best, if at all, when they are pure functions with <strong>no</strong> side effects. This is a throwback to functional programming, and my personal least-favorite <a href="http://www-swiss.ai.mit.edu/projects/scheme/">Scheme</a>.</p>
<p>I still favor these methods to the rather Draconian no-shared-mutable-state edict of <a href="http://www.erlang.org/">Erlang</a>:</p>
<blockquote><p>
<strong>Carl Franklin</strong>: There's no shared memory, right?</p>
<p><strong>Larry O'Brien</strong>: Oh, that's huge.</p>
<p><strong>Carl Franklin</strong>: Between processes?</p>
<p><strong>Larry O'Brien</strong>: That's a huge thing. Really to make Concurrency work at the language level, the number one thing that you want to get rid of is shared mutable state. </p>
<p><strong>Carl Franklin</strong>: Yup.</p>
<p><strong>Larry O'Brien</strong>: Erlang is single assignment to variables...
</p></blockquote>
<p>This is why I think <a href="http://research.microsoft.com/~nick/polyphony/intro.htm">Polyphonic C#</a> is a nice try but gives me some of the same headaches I felt at the start of this post.</p>
<p>It is ultimately a trade-off between shared mutable state (and thus performance) a la Futures and functional programming, and clarity (and thus less performance) a la STM. I think this trade-off is a familiar one to most people in this field. Moreover, I'll say that this trade-off is as innate to our field as <a href="http://www.techweb.com/encyclopedia/defineterm.jhtml?term=Brook's+law">Brooks' Law</a>.</p>
<p>I maintain that abstractions like STM and Futures are going to be very important for us software developers in the coming decade if we are to make affordable full use of the next wave of hardware.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Church Rosser Theorem]]></title>
<link>http://un1crom.wordpress.com/?p=195</link>
<pubDate>Wed, 16 Jul 2008 13:19:24 +0000</pubDate>
<dc:creator>un1crom</dc:creator>
<guid>http://un1crom.wordpress.com/?p=195</guid>
<description><![CDATA[This is one fun little theorem. 
Basically&#8230; if symbolic systems terminate (program halts/gives]]></description>
<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Church-Rosser_theorem">This is one fun little theorem. </a></p>
<p>Basically... if symbolic systems terminate (program halts/gives output), the terminating expression is independent of how the rules were applied.</p>
<p><a href="http://en.wikipedia.org/wiki/Confluence_(term_rewriting)">You get "confluence" out of this.</a></p>
<p>You probably are thinking, "and so what does this have to do with my life?"</p>
<p>a) maybe nothing if arithmetic never enters your life (unlikely)</p>
<p>b) it's extremely good to know when you use functional programming that you can get to the same answer with many different ways of writing something.  <a href="http://en.wikipedia.org/wiki/Functional_programming">For good overview of functional programming, go here.</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Concurrency &amp; Coordination With Futures in C#]]></title>
<link>http://dvanderboom.wordpress.com/2008/07/03/concurrency-with-futures/</link>
<pubDate>Fri, 04 Jul 2008 01:14:32 +0000</pubDate>
<dc:creator>Dan Vanderboom</dc:creator>
<guid>http://dvanderboom.wordpress.com/2008/07/03/concurrency-with-futures/</guid>
<description><![CDATA[A future is a proxy or placeholder for a value that may not yet be known, usually because the calcul]]></description>
<content:encoded><![CDATA[<p>A future is a proxy or placeholder for a value that may not yet be known, usually because the calculation is time consuming.&#160; It is used as a synchronization construct, and it is an effective way to define dependencies among computations that will execute when all of their factors have been calculated, or in other words, to construct an expression tree with each node potentially computing in parallel.&#160; According to the <a href="http://en.wikipedia.org/wiki/Futures_and_promises" target="_blank">Wikipedia article</a> on futures and promises, using them can dramatically reduce latency in distributed systems.</p>
<p>Damon pointed out that the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=348F73FD-593D-4B3C-B055-694C50D2B0F3&#38;displaylang=en" target="_blank">Parallel Extensions library</a> contains a Future&#60;T&#62; class, so I started looking around for examples and explanations of how they work, what the syntax is like, and I ran across <a href="http://blogs.msdn.com/pfxteam/archive/2008/02/29/7960146.aspx" target="_blank">a frightening example</a> implementing the asynchronous programming model with Future&#60;T&#62;, as well as going in the other direction, <a href="http://blogs.msdn.com/pfxteam/archive/2008/03/16/8272833.aspx" target="_blank">wrapping an APM implementation with Future&#60;T&#62;</a>.&#160; Other articles give pretty good <a href="http://www.liensberger.it/web/blog/?p=162" target="_blank">explanations</a> but trivial examples.&#160; From what I gathered briefly, the ContinueWith method for specifying the next step of calculation to process doesn’t seem to provide an intuitive way to indicate that several calculations may be depending upon the current one (unless it can be called multiple times?).&#160; Using ContinueWith, you’re always specifying <strong>forward</strong> the calculation task that depends on the current future object.&#160; It also surprised me a little that Future inherits from Task, because my understanding of a future is that it’s primarily defined as a value-holding object.&#160; But considering that a future really holds an expression that needs to be calculated, making Future a Task doesn’t seem so odd.</p>
<p>So I decided to implement my own Future&#60;T&#62; class before looking at the parallel extensions library too deeply.&#160; I didn’t want to prejudice my solution, because I wanted to make an exercise of it and see what I would naturally come up with.</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
<p>Though I tried avoiding prejudice, I still wound up characterizing it in my head as an task, and thought that a future would simply be a pair of Action and Reaction methods (both of the Action delegate type).&#160; The Action would execute and could do whatever it liked, including evaluate some expression and store it in a variable.&#160; If the Action completed, the Reaction method (a continuation) would run, and these could be specified using lambdas.&#160; Because I was storing the results in a local variable (result), swallowed up and made accessible with a closure, I didn’t see a need for a Value property in the future and therefore no need to make the type generic.&#160; Ultimately I thought it silly to have a Reaction method, since anything you needed to happen sequentially after a successful Action, you could simply store at the end of the Action method itself.</p>
<pre><font size="2"><span style="color:#2b91af;">FutureTask </span>task = <span style="color:blue;">new </span><span style="color:#2b91af;">FutureTask</span>(
    () =&#62; result = CalculatePi(10),
    () =&#62; <span style="color:blue;">new </span><span style="color:#2b91af;">FutureTask</span>(
        () =&#62; result += <span style="color:#a31515;">&#34;...&#34;</span>,
        () =&#62; <span style="color:#2b91af;">Console</span>.WriteLine(result),
        ex2 =&#62; <span style="color:#2b91af;">Console</span>.WriteLine(<span style="color:#a31515;">&#34;ex2: &#34; </span>+ ex2.Message)),
    ex1 =&#62; <span style="color:#2b91af;">Console</span>.WriteLine(<span style="color:#a31515;">&#34;ex1: &#34; </span>+ ex1.Message));</font></pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>The syntax is what I was most concerned with, and as I started playing around with nesting of futures to compose my calculation, I started to feel like I was onto something.&#160; After all, it was almost starting to resemble some of the F# code I’ve been looking at, and I took that style of functional composition to be a good sign.&#160; As you can see from the code above, I also include a constructor parameter of type Action&#60;Exception&#62; for compensation logic to run in the event that the original action fails.&#160; (The result variable is a string, CalculatePi returns a string, and so the concatenation of the ellipsis really does make sense here.)</p>
<p>The problem that started nagging me was the thought that a composite computation of future objects might not be able to be defined all in one statement like this, not building the dependency tree from the bottom up.&#160; You can really only define the most basic factors (the leaf nodes of a dependency tree) at the beginning this way, and then the expressions that depend directly upon those leaf nodes, etc.&#160; What if you have 50 different starting future values, and you can only proceed with the next step in the calculation once 5 of those specific futures have completed evaluation?&#160; How would you express those dependencies with this approach?</p>
<p>That’s when I started to think about futures as top-down hierarchical data container objects, instead of tasks that have pointers to some next task in a sequence.&#160; I created a Future&#60;T&#62; class whose constructor takes an optional name (to aid debugging), a method of type Func&#60;T&#62; (which is a simple expression, supplied as a lambda in my examples), and finally an optional params list of other Future&#60;T&#62; objects on which that future value depends.</p>
<p>The first two futures in the code below start calculating pi (3.1415926535) and omega (which I made up to be a string of 9s).&#160; They have no dependencies, so they can start calculating right away.&#160; The paren future has two dependencies, supplied as two parameters at the end of the argument list: pi and omega.&#160; You can see that the values pi.Value and omega.Value are used in the expression, which will simply surround the concatenated string value with parentheses and spaces.</p>
<pre><font size="2"><span style="color:blue;">var </span>pi = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(<span style="color:#a31515;">&#34;pi&#34;</span>, () =&#62; CalculatePi(10));
<span style="color:blue;">var </span>omega = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(<span style="color:#a31515;">&#34;omega&#34;</span>, () =&#62; CalculateOmega());

<span style="color:blue;">var </span>paren = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(<span style="color:#a31515;">&#34;parenthesize&#34;</span>, () =&#62; Parenthesize(pi.Value + <span style="color:#a31515;">&#34; &#60; &#34; </span>+ omega.Value), pi, omega);

<span style="color:blue;">var </span>result = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(<span style="color:#a31515;">&#34;bracket&#34;</span>, () =&#62; Bracket(paren.Value), paren);</font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Finally, the result future has a dependency on the paren future.&#160; This surrounds the result of paren.Value with brackets and spaces.&#160; Because the operations here are trivial, I’ve added Thread.Sleep statements to all of these methods to simulate more computationally expensive work.</p>
<p><a href="http://dvanderboom.files.wordpress.com/2008/07/image1.png"><img style="border-width:0;" height="219" alt="Dependencies Among Futures" src="http://dvanderboom.files.wordpress.com/2008/07/image-thumb1.png" width="240" border="0" /></a> </p>
<p>The program starts calculating pi and omega concurrently, and then immediately builds the paren future, which because of its dependencies waits for completion of the pi and omega futures.&#160; But it doesn’t block the thread.&#160; Execution continues immediately to build the result future, and then moves on to the next part of the program.&#160; When each part of the expression, each future, completes, it will set a Complete boolean property to true and invoke a Completed event.&#160; Any attempt to access the Value property of one of these futures <strong>will</strong> block the thread until it (and all of the futures it depends on) have completed evaluation.</p>
<p>Furthermore, if an exception occurs, all of the futures that depend on it will no longer attempt to evaluate, and the exceptions will be thrown as part of an AggregateException when accessing the Value property.&#160; This AggregateException contains all of the individual exceptions that were thrown as part of evaluating each future expression.&#160; If both pi and omega fail, result should be able to hand me a list of all Exceptions below it in the tree structure that automatically gets formed.</p>
<p>There are two bits of code I added as icing on this cake.&#160; The first is the use of the implicit operator to convert a variable of type Future&#60;T&#62; to type T.&#160; In other words, if you have a Future&#60;string&#62; called result, you can now pass result into methods where a string parameter is expected, etc.&#160; In the code listing at the end of the article, you’ll notice that I reference pi and omega instead of pi.Value and omega.Value (as in the code snippet above).</p>
<pre><font size="2"><span style="color:blue;">public static implicit operator </span>T(<span style="color:#2b91af;">Future</span>&#60;T&#62; Future)
{
    <span style="color:blue;">return </span>Future.Value;
}</font></pre>
<p>The other helpful bit is an override of ToString, which allows you to hover over a future variable in debug mode and see its name (if you named it), whether it’s Complete or Incomplete, and any errors encountered during evaluation.</p>
<pre><font size="2"><span style="color:blue;">public override string </span>ToString()
{
    <span style="color:blue;">return </span>Name + <span style="color:#a31515;">&#34;, &#34; </span>+ (Complete ? <span style="color:#a31515;">&#34;Complete&#34; </span>: <span style="color:#a31515;">&#34;Incomplete&#34;</span>) + (Error != <span style="color:blue;">null </span>? <span style="color:#a31515;">&#34;Error=&#34; </span>+ Error.Message : <span style="color:blue;">string</span>.Empty);
}</font></pre>
<p><a href="http://dvanderboom.files.wordpress.com/2008/07/image.png"><img style="border-width:0;" height="76" alt="Debug Experience of Future" src="http://dvanderboom.files.wordpress.com/2008/07/image-thumb.png" width="476" border="0" /></a> </p>
<p>What I’d really like to do is have the ability to construct this composite expression in a hierarchical form in the language, with a functionally composed syntax, replacing any parameter T with a Future&#60;T&#62;, something like this:</p>
<pre><font size="2"><span style="color:blue;">var </span>result = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(<span style="color:#a31515;">&#34;bracket&#34;</span>, () =&#62; Bracket(
    <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(<span style="color:#a31515;">&#34;parenthesize&#34;</span>, () =&#62; Parenthesize(
        <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(<span style="color:#a31515;">&#34;pi&#34;</span>, () =&#62; CalculatePi(10))
        + <span style="color:#a31515;">&#34; &#60; &#34; </span>+
        <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(<span style="color:#a31515;">&#34;omega&#34;</span>, () =&#62; CalculateOmega())
    ))
));</font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The Bracket and Parenthesize methods both require a string, but I give them an object that will at some point (“in the future”) evaluate to a string.&#160; Another term used for <strong>future</strong> is <strong>promise</strong>, although there is a distinction in some languages that support both, but you can think in terms of giving those methods the promise that they’ll get a string later, at which time they can proceed with their own evaluation.&#160; This effectively creates lazy evaluation, sometimes referred to as normal-order evaluation.</p>
<p>There are a few problems with this code, however.&#160; First of all, though it’s composed functionally from the top down and returns the correct answer, it takes too long to do it: about 8 seconds instead of 4.&#160; That means it’s processing all of the steps sequentially.&#160; This happens because the future objects we’re handing to the Parenthesize and Bracket methods have to be converted from Future&#60;string&#62; to string before they can be evaluated in the expression, and doing that activates the implicit operator, which executes the Value property getter.&#160; This completely destroys the asynchronous behavior we’re going for, by insisting on resolving it immediately with the wait built-into the Value property.&#160; The string concatenation expression evaluates sequentially one piece at a time, and when that’s done, the next level up evaluates, and so on.</p>
<p>The solution is to declare our futures as factors we depend on at each level, which start them executing right away due to C#’s order of evaluation, and declare the operations we want to perform in terms of those predefined futures.&#160; After a few hours of rearranging definitions, declaration order, and experimenting with many other details (including a brief foray into being more indirect with Func&#60;Future&#60;T&#62;&#62;), this is the working code I came up with:</p>
<pre><font size="2"><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62; FuturePi = <span style="color:blue;">null</span>, FutureOmega = <span style="color:blue;">null</span>, FutureConcat = <span style="color:blue;">null</span>, FutureParen = <span style="color:blue;">null</span>;

<span style="color:blue;">var </span>result = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(
    () =&#62; Bracket(FutureParen),
    (FutureParen = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(
        () =&#62; Parenthesize(FutureConcat),
        (FutureConcat = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:#2b91af;">String</span>&#62;(
            () =&#62; FuturePi + <span style="color:#a31515;">&#34; &#60; &#34; </span>+ FutureOmega,
            (FuturePi = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(() =&#62; CalculatePi(10))),
            (FutureOmega = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(() =&#62; CalculateOmega()))
        ))
    ))
);</font></pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>In F# and other more functional languages, I imagine we could use let statements to define and assign these variables as part of the overall expression, instead of having to define the variables in a separate statement as shown here.</p>
<p>The Future&#60;T&#62; class I wrote works fairly well for exploration and study of futures and the possible syntax to define them and access their values, and I’ll share it so that you can experiment with it if you like, but understand that this is (even more so than usual) not production ready code.&#160; I’m making some very naive assumptions, not taking advantage of any task managers or thread pools, there is no intelligent scheduling going on, and I haven’t tested this in any real world applications.&#160; With that disclaimer out of the way, here it is, complete with the consuming test code.</p>
<pre><font size="2"><span style="color:blue;">using </span>System;
<span style="color:blue;">using </span>System.Collections.Generic;
<span style="color:blue;">using </span>System.Threading;
<span style="color:blue;">using </span>System.Linq;

<span style="color:blue;">namespace </span>FutureExpressionExample
{
    <span style="color:blue;">class </span></font><font size="2"><span style="color:#2b91af;">Program
    </span>{
        <span style="color:blue;">static void </span>Main(<span style="color:blue;">string</span>[] args)
        {
            <span style="color:#2b91af;">DateTime </span>StartTime = <span style="color:#2b91af;">DateTime</span>.Now;

            <span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62; FuturePi = <span style="color:blue;">null</span>, FutureOmega = <span style="color:blue;">null</span>, FutureConcat = <span style="color:blue;">null</span>, FutureParen = <span style="color:blue;">null</span>;

            <span style="color:blue;">var </span>result = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(<span style="color:#a31515;">&#34;bracket&#34;</span>,
                () =&#62; Bracket(FutureParen),
                (FutureParen = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(<span style="color:#a31515;">&#34;parenthesize&#34;</span>,
                    () =&#62; Parenthesize(FutureConcat),
                    (FutureConcat = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:#2b91af;">String</span>&#62;(<span style="color:#a31515;">&#34;concat&#34;</span>,
                        () =&#62; FuturePi + <span style="color:#a31515;">&#34; &#60; &#34; </span>+ FutureOmega,
                        (FuturePi = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(<span style="color:#a31515;">&#34;pi&#34;</span>, () =&#62; CalculatePi(10))),
                        (FutureOmega = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(<span style="color:#a31515;">&#34;omega&#34;</span>, () =&#62; CalculateOmega()))
                    ))
                ))
            );

            </font><font size="2"><span style="color:green;">/* Alternative

            // first group of expressions evaluating in parallel
            var pi = new Future&#60;string&#62;(&#34;pi&#34;, () =&#62; CalculatePi(10));
            var omega = new Future&#60;string&#62;(&#34;omega&#34;, () =&#62; CalculateOmega());

            // a single future expression dependent on all of the futures in the first group
            var paren = new Future&#60;string&#62;(&#34;parenthesize&#34;, () =&#62; Parenthesize(pi + &#34; &#60; &#34; + omega), pi, omega);

            // another single future expression dependent on the paren future
            var result = new Future&#60;string&#62;(&#34;bracket&#34;, () =&#62; Bracket(paren), paren);

            */

            </span><span style="color:#2b91af;">Console</span>.WriteLine(<span style="color:#a31515;">&#34;Do other stuff while calculation occurs...&#34;</span>);

            </font><font size="2"><span style="color:blue;">try
            </span>{
                <span style="color:#2b91af;">Console</span>.WriteLine(<span style="color:#a31515;">&#34;\n&#34; </span>+ result);
            }
            <span style="color:blue;">catch </span>(<span style="color:#2b91af;">AggregateException </span>ex)
            {
                <span style="color:#2b91af;">Console</span>.WriteLine(<span style="color:#a31515;">&#34;\n&#34; </span>+ ex.Message);
            }

            <span style="color:#2b91af;">TimeSpan </span>ts = <span style="color:#2b91af;">DateTime</span>.Now - StartTime;
            <span style="color:#2b91af;">Console</span>.WriteLine(<span style="color:#a31515;">&#34;\n&#34; </span>+ ts.TotalSeconds.ToString() + <span style="color:#a31515;">&#34; seconds&#34;</span>);

            <span style="color:#2b91af;">Console</span>.ReadKey();
        }

        <span style="color:blue;">static string </span>CalculatePi(<span style="color:blue;">int </span>NumberDigits)
        {
            </font><font size="2"><span style="color:green;">//throw new ApplicationException(&#34;Failed to calculate Pi&#34;);
            </span><span style="color:#2b91af;">Thread</span>.Sleep(3000);
            <span style="color:blue;">return </span><span style="color:#a31515;">&#34;3.1415926535&#34;</span>;
        }

        <span style="color:blue;">static string </span>CalculateOmega()
        {
            </font><font size="2"><span style="color:green;">//throw new ApplicationException(&#34;Failed to calculate Omega&#34;);
            </span><span style="color:#2b91af;">Thread</span>.Sleep(3000);
            <span style="color:blue;">return </span><span style="color:#a31515;">&#34;999999999999999&#34;</span>;
        }

        <span style="color:blue;">static string </span>Parenthesize(<span style="color:blue;">string </span>Text)
        {
            <span style="color:#2b91af;">Thread</span>.Sleep(500);
            <span style="color:blue;">return </span><span style="color:#a31515;">&#34;( &#34; </span>+ Text + <span style="color:#a31515;">&#34; )&#34;</span>;
        }

        <span style="color:blue;">static string </span>Bracket(<span style="color:blue;">string </span>Text)
        {
            <span style="color:#2b91af;">Thread</span>.Sleep(500);
            <span style="color:blue;">return </span><span style="color:#a31515;">&#34;[ &#34; </span>+ Text + <span style="color:#a31515;">&#34; ]&#34;</span>;
        }
    }

    <span style="color:blue;">public class </span><span style="color:#2b91af;">Future</span>&#60;T&#62; : </font><font size="2"><span style="color:#2b91af;">IDisposable
    </span>{
        <span style="color:blue;">public string </span>Name { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
        <span style="color:blue;">public bool </span>Complete { <span style="color:blue;">get</span>; <span style="color:blue;">protected set</span>; }
        <span style="color:blue;">public </span><span style="color:#2b91af;">Exception </span>Error { <span style="color:blue;">get</span>; <span style="color:blue;">protected set</span>; }

        <span style="color:blue;">protected </span><span style="color:#2b91af;">Func</span>&#60;T&#62; Expression { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }

        <span style="color:blue;">protected </span><span style="color:#2b91af;">List</span>&#60;<span style="color:#2b91af;">Future</span>&#60;T&#62;&#62; Factors;
        <span style="color:blue;">protected </span><span style="color:#2b91af;">List</span>&#60;<span style="color:#2b91af;">Future</span>&#60;T&#62;&#62; FactorsCompleted;
        <span style="color:blue;">protected </span><span style="color:#2b91af;">List</span>&#60;<span style="color:#2b91af;">Future</span>&#60;T&#62;&#62; FactorsFailed;

        <span style="color:blue;">public event </span><span style="color:#2b91af;">Action</span>&#60;<span style="color:#2b91af;">Future</span>&#60;T&#62;&#62; Completed;
        <span style="color:blue;">protected void </span>OnCompleted()
        {
            Complete = <span style="color:blue;">true</span>;

            <span style="color:blue;">if </span>(Completed != <span style="color:blue;">null</span>)
                Completed(<span style="color:blue;">this</span>);
        }

        <span style="color:blue;">private </span>T _Value;
        <span style="color:blue;">public </span>T Value
        {
            </font><font size="2"><span style="color:blue;">get
            </span>{
                </font><font size="2"><span style="color:green;">// block until complete
                </span><span style="color:blue;">while </span>(!Complete)
                {
                    <span style="color:#2b91af;">Thread</span>.Sleep(1);
                }

                <span style="color:blue;">if </span>(Exceptions.Count &#62; 0)
                    <span style="color:blue;">throw new </span><span style="color:#2b91af;">AggregateException</span>(Exceptions);

                <span style="color:blue;">return </span>_Value;
            }
            <span style="color:blue;">private set </span>{ _Value = <span style="color:blue;">value</span>; }
        }

        <span style="color:blue;">public </span><span style="color:#2b91af;">List</span>&#60;<span style="color:#2b91af;">Exception</span>&#62; Exceptions
        {
            </font><font size="2"><span style="color:blue;">get
            </span>{
                <span style="color:blue;">var </span>list = <span style="color:blue;">new </span><span style="color:#2b91af;">List</span>&#60;<span style="color:#2b91af;">Exception</span>&#62;();

                <span style="color:blue;">foreach </span>(<span style="color:#2b91af;">Future</span>&#60;T&#62; Factor <span style="color:blue;">in </span>Factors)
                {
                    list.AddRange(Factor.Exceptions);
                }

                <span style="color:blue;">if </span>(Error != <span style="color:blue;">null</span>)
                    list.Add(Error);

                <span style="color:blue;">return </span>list;
            }
        }

        <span style="color:blue;">public static implicit operator </span>T(<span style="color:#2b91af;">Future</span>&#60;T&#62; Future)
        {
            <span style="color:blue;">return </span>Future.Value;
        }

        </font><font size="2"><span style="color:green;">// naming a Future is optional
        </span><span style="color:blue;">public </span>Future(<span style="color:#2b91af;">Func</span>&#60;T&#62; Expression, <span style="color:blue;">params </span><span style="color:#2b91af;">Future</span>&#60;T&#62;[] Factors) : <span style="color:blue;">this</span>(<span style="color:#a31515;">&#34;&#60;not named&#62;&#34;</span>, Expression, Factors) { }

        <span style="color:blue;">public </span>Future(<span style="color:blue;">string </span>Name, <span style="color:#2b91af;">Func</span>&#60;T&#62; Expression, <span style="color:blue;">params </span><span style="color:#2b91af;">Future</span>&#60;T&#62;[] Factors)
        {
            <span style="color:blue;">this</span>.Name = Name;
            <span style="color:blue;">this</span>.Expression = Expression;
            <span style="color:blue;">this</span>.Factors = <span style="color:blue;">new </span><span style="color:#2b91af;">List</span>&#60;<span style="color:#2b91af;">Future</span>&#60;T&#62;&#62;(Factors);

            FactorsCompleted = <span style="color:blue;">new </span><span style="color:#2b91af;">List</span>&#60;<span style="color:#2b91af;">Future</span>&#60;T&#62;&#62;();
            FactorsFailed = <span style="color:blue;">new </span><span style="color:#2b91af;">List</span>&#60;<span style="color:#2b91af;">Future</span>&#60;T&#62;&#62;();

            <span style="color:blue;">foreach </span>(<span style="color:#2b91af;">Future</span>&#60;T&#62; Factor <span style="color:blue;">in this</span>.Factors)
            {
                <span style="color:blue;">if </span>(Factor.Complete)
                    FactorsCompleted.Add(Factor);
                </font><font size="2"><span style="color:blue;">else
                    </span>Factor.Completed += <span style="color:blue;">new </span><span style="color:#2b91af;">Action</span>&#60;<span style="color:#2b91af;">Future</span>&#60;T&#62;&#62;(Factor_Completed);
            }

            </font><font size="2"><span style="color:green;">// there may not be any factors, or they may all be complete
            </span><span style="color:blue;">if </span>(FactorsCompleted.Count == <span style="color:blue;">this</span>.Factors.Count)
                Expression.BeginInvoke(ReceiveCallback, <span style="color:blue;">null</span>);
        }

        <span style="color:blue;">private void </span>Factor_Completed(<span style="color:#2b91af;">Future</span>&#60;T&#62; Factor)
        {
            <span style="color:blue;">if </span>(!FactorsCompleted.Contains(Factor))
                FactorsCompleted.Add(Factor);

            <span style="color:blue;">if </span>(Factor.Error != <span style="color:blue;">null </span>&#38;&#38; !FactorsFailed.Contains(Factor))
                FactorsFailed.Add(Factor);

            Factor.Completed -= <span style="color:blue;">new </span><span style="color:#2b91af;">Action</span>&#60;<span style="color:#2b91af;">Future</span>&#60;T&#62;&#62;(Factor_Completed);

            <span style="color:blue;">if </span>(Exceptions.Count &#62; 0)
            {
                Dispose();
                OnCompleted();
                <span style="color:blue;">return</span>;
            }

            <span style="color:blue;">if </span>(FactorsCompleted.Count == Factors.Count)
                Expression.BeginInvoke(ReceiveCallback, <span style="color:blue;">null</span>);
        }

        <span style="color:blue;">private void </span>ReceiveCallback(<span style="color:#2b91af;">IAsyncResult </span>AsyncResult)
        {
            </font><font size="2"><span style="color:blue;">try
            </span>{
                Value = Expression.EndInvoke(AsyncResult);
            }
            <span style="color:blue;">catch </span>(<span style="color:#2b91af;">Exception </span>ex)
            {
                Error = ex;
            }

            Dispose();

            </font><font size="2"><span style="color:green;">// computation is completed, regardless of whether it succeeded or failed
            </span>OnCompleted();
        }

        <span style="color:blue;">public void </span>Dispose()
        {
            <span style="color:blue;">foreach </span>(<span style="color:#2b91af;">Future</span>&#60;T&#62; Factor <span style="color:blue;">in </span>Factors)
            {
                Factor.Completed -= <span style="color:blue;">new </span><span style="color:#2b91af;">Action</span>&#60;<span style="color:#2b91af;">Future</span>&#60;T&#62;&#62;(Factor_Completed);
            }
        }

        </font><font size="2"><span style="color:green;">// helpful for debugging
        </span><span style="color:blue;">public override string </span>ToString()
        {
            <span style="color:blue;">return </span>Name + <span style="color:#a31515;">&#34;, &#34; </span>+ (Complete ? <span style="color:#a31515;">&#34;Complete&#34; </span>: <span style="color:#a31515;">&#34;Incomplete&#34;</span>) + (Error != <span style="color:blue;">null </span>? <span style="color:#a31515;">&#34;, Error=&#34; </span>+ Error.Message : <span style="color:blue;">string</span>.Empty);
        }
    }

    <span style="color:blue;">public class </span><span style="color:#2b91af;">AggregateException </span>: </font><font size="2"><span style="color:#2b91af;">Exception
    </span>{
        <span style="color:blue;">public </span><span style="color:#2b91af;">List</span>&#60;<span style="color:#2b91af;">Exception</span>&#62; Exceptions;

        <span style="color:blue;">public </span>AggregateException(<span style="color:#2b91af;">IEnumerable</span>&#60;<span style="color:#2b91af;">Exception</span>&#62; Exceptions)
        {
            <span style="color:blue;">this</span>.Exceptions = <span style="color:blue;">new </span><span style="color:#2b91af;">List</span>&#60;<span style="color:#2b91af;">Exception</span>&#62;(Exceptions);
        }

        <span style="color:blue;">public override string </span>Message
        {
            </font><font size="2"><span style="color:blue;">get
            </span>{
                <span style="color:blue;">string </span>message = <span style="color:blue;">string</span>.Empty;
                <span style="color:blue;">foreach </span>(<span style="color:#2b91af;">Exception </span>ex <span style="color:blue;">in </span>Exceptions)
                {
                    message += ex.Message + <span style="color:#a31515;">&#34;\n&#34;</span>;
                }
                <span style="color:blue;">return </span>message;
            }
        }
    }
}</font></pre>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Improving exception-management in OCaml]]></title>
<link>http://dutherenverseauborddelatable.wordpress.com/?p=105</link>
<pubDate>Wed, 02 Jul 2008 14:46:28 +0000</pubDate>
<dc:creator>yoric</dc:creator>
<guid>http://dutherenverseauborddelatable.wordpress.com/?p=105</guid>
<description><![CDATA[Short version
Catch me if you can is a small library for OCaml 3.10. The latest release is version 0]]></description>
<content:encoded><![CDATA[<h2 style="text-align:justify;">Short version</h2>
<p style="text-align:justify;">Catch me if you can is a small library for OCaml 3.10. The latest release is version 0.2, which you may find <a href="http://www.univ-orleans.fr/lifo/Members/David.Teller/software/exceptions/catch_0_2.tgz">here</a>. This library improves management of errors in OCaml. It is released under the LGPL licence. It has been written by David Teller, Arnaud Spiwack, Till Varoquaux and Gabriel Scherer.</p>
<p><!--more--></p>
<hr />
<h2><strong>Long version<br />
</strong></h2>
<p align="justify">As all languages of the ML family -- and most modern languages indeed -- OCaml permits the management of exceptional situations using <em>exceptions</em>. This mechanism lets programmer register protected sections of code, as well as <em>exception handlers</em> to handle any exception which may be <em>raised</em> during the execution of a protected section. Whenever an exception is <em>raised</em>, the protected section of code is immediately stopped and the corresponding exception handler is executed instead. In addition, exceptions may convey some information regarding the nature of the exceptional circumstance.</p>
<p align="justify">In OCaml, the mechanism is fast, it's convenient and it's type-safe, much like the rest of the language (barring any type-unsafe interaction with C). However, a few things are missing. If we consider the rest of the language, exceptions are both heavyweight and clumsy: each exception must be declared before being used and there's no way to introduce a polymorphic type parameter in the exception. In addition, languages such as Java offer to important features missing in OCaml: automatic case coverage and exception hierarchies. While <a href="http://caml.inria.fr/pub/old_caml_site/ocamlexc/ocamlexc.htm">a nice tool</a> exists  to provide case coverage for exceptions in OCaml, this tool is complex and  unfortunately unmaintained.</p>
<p align="justify"><em>Catch me if you can</em> offers an alternative mechanism, comparable to ML exceptions, to handle errors. In comparison with OCaml's native exception mechanism, this library adds:</p>
<ul>
<li>automatic inference of exceptions (i.e. no need to declare your exceptions, unless you want to)</li>
<li>more flexible exceptions (i.e. exceptions may have polymorphic type parameters, constraints, etc.)</li>
<li>hierarchies (i.e. an IOException is a sub-case of Exception and a super-case of NetworkException)</li>
<li>case coverage (i.e. the compiler can tell you if you forgot a case or sometimes if you wrote useless ones)</li>
<li>conditional success handlers (i.e. do something with the result in case of success)</li>
<li>conditional success-and-failure handlers (i.e. "finally").</li>
</ul>
<p style="text-align:justify;">To attain this, we replace the mechanism of exceptions by an error monad, we replace exception constructors with polymorphic variants and we introduce a dose of syntactic sugar.</p>
<hr />
<h2>Examples</h2>
<h3>Expression evaluator</h3>
<p>Let's write a simple expression evaluator for the following set of expressions:</p>
<p>[sourcecode lang='python']<br />
type expr =<br />
  &#124; Value of float<br />
  &#124; Div     of expr * expr<br />
  &#124; Add    of expr * expr<br />
  &#124; Mult   of expr * expr<br />
  &#124; Subs  of expr * expr<br />
[/sourcecode]</p>
<p>These may be evaluated using the following function:</p>
<p>[sourcecode lang='python']<br />
let rec eval = function<br />
 &#124; Value x    -> x<br />
 &#124; Add (x,y) -> eval x +. eval y<br />
 &#124; Mult(x,y)  -> eval x *. eval y<br />
 &#124; Div(x,y)   -> eval x /. eval y<br />
 &#124; Subs(x,y) -> eval x -. eval y<br />
[/sourcecode]</p>
<p style="text-align:justify;">Of course, this function is bound to fail in case of division by zero. While this is expected, there is nothing in the source code -- much less in the type of the function -- to let us know which exception will be raised in case of division by zero.</p>
<p>An alternative would be to add manual error checking, as follows:</p>
<p>[sourcecode lang='python']<br />
type ('a, 'b) result =<br />
 &#124; Ok of 'a<br />
 &#124; Error of 'b</p>
<p>let rec eval = function<br />
 &#124; Value x    -> OK x<br />
 &#124; Add (x,y) -> (match eval x with<br />
                      &#124; Error e -> Error e<br />
                      &#124; Ok x' ->  match eval y with<br />
                               &#124; Error e -> Error e<br />
                               &#124; Ok y'    -> Ok (x' +. y'))<br />
 &#124; Mult (x,y) -> (match eval x with<br />
                      &#124; Error e -> Error e<br />
                      &#124; Ok x' ->  match eval y with<br />
                               &#124; Error e -> Error e<br />
                               &#124; Ok y'    -> Ok (x' *. y'))<br />
 &#124; Div (x,y) -> (match eval x with<br />
                      &#124; Error e -> Error e<br />
                      &#124; Ok x' ->  match eval y with<br />
                               &#124; Error e -> Error e<br />
                               &#124; Ok y'    -> if y' = 0. then Error "Division by zero"<br />
                                                else              Ok (x' /. y'))<br />
 &#124; Subs (x,y) -> (match eval x with<br />
                      &#124; Error e -> Error e<br />
                      &#124; Ok x' ->  match eval y with<br />
                               &#124; Error e -> Error e<br />
                               &#124; Ok y'    -> Ok (x' -. y'))<br />
(*eval : expr -> (float, string) result*)<br />
[/sourcecode]</p>
<p style="text-align:justify;">After this transformation, the type of the exception appears in the type of <code>eval</code> -- here, we used strings, but anything else would have been fine. Of course, the downside is that this is unreadable. Well, what about the following ?</p>
<p>[sourcecode lang='python']<br />
let rec eval = function<br />
 &#124; Value x    -> return x<br />
 &#124; Add (x,y) -> perform with module Error<br />
                        x' <-- eval x;<br />
                        y' <-- eval y;<br />
                        return (x' +. y')<br />
 &#124; Mult (x,y) -> perform with module Error<br />
                        x' <-- eval x;<br />
                        y' <-- eval y;<br />
                        return (x' *. y')<br />
 &#124; Div (x,y) -> perform with module Error<br />
                        x' <-- eval x;<br />
                        y' <-- eval y;<br />
                        if y'=0. then throw "Division by zero"<br />
                        else            return (x' /. y')<br />
 &#124; Subs (x,y) -> perform with module Error<br />
                        x' <-- eval x;<br />
                        y' <-- eval y;<br />
                        return (x' -. y')<br />
(*eval : expr -> (float, string) result*)<br />
[/sourcecode]</p>
<p style="text-align:justify;">This extract uses [our customized version of] Pa_monad (included in the package), which brings syntactic support for monads. While this is more verbose than the original version, it's also safer, insofar as we can guarantee that exceptions won't remain uncaught.</p>
<p>Still too long? Then what about using the appropriate operators?</p>
<p>[sourcecode lang='python']<br />
open Error.Operators<br />
let rec eval = function<br />
 &#124; Value x    -> x<br />
 &#124; Add (x,y) -> eval x +. eval y<br />
 &#124; Mult(x,y) -> eval x *. eval y<br />
 &#124; Div(x,y)   -> eval x /. eval y<br />
 &#124; Subs(x,y) -> eval x -. eval y<br />
[/sourcecode]</p>
<p>Except for the module opening, that's the same thing as our first listing. Just with the added safety.</p>
<h3>Throwing, catching and hierarchies</h3>
<p>By the way, the type of the result is</p>
<p>[sourcecode lang='python']<br />
(*eval : expr -> (float, [> `Arithmetic of (unit, [> `Div_by_zero of (unit, _) exc ]) exc ]) result*)<br />
[/sourcecode]</p>
<p>That is, eval may either succeed and return a float or fail and return an arithmetic exception, which also turns out to be a division by zero. That's classes of exceptions.</p>
<p>With our syntactic sugar, raising such an exception is done by</p>
<p>[sourcecode lang='python']<br />
throw (exception Arithmetic (); Div_by_zero ())<br />
[/sourcecode]</p>
<p style="text-align:justify;">Note that we could have put some content instead of <code>()</code>. Note that exceptions are typed as they appear in the code and don't need to be declared (if you wonder, polymorphic variants are involved in this).</p>
<p>Of course, various kinds of exceptions may be combined, as in the following extract:</p>
<p>[sourcecode lang='python']<br />
match ... with<br />
&#124; 1 -> throw (exception Arithmetic (); Div_by_zero ())<br />
&#124; 2 -> throw (exception Arithmetic (); Overflow "by gosh !")<br />
&#124; 3 -> throw (exception IO file_descr)<br />
&#124; ...<br />
(*<br />
('a, [> `Arithmetic of (unit, [> `Div_by_zero of (unit, _) exc<br />
                                     &#124;   `Overflow of (string, _)   exc]) exc<br />
     &#124;   `IO of (int, [`> ]) exc ]) result*)<br />
*)<br />
[/sourcecode]</p>
<p>While the type of the expression is difficult to read, catching is easy</p>
<p>[sourcecode lang='python']<br />
attempt ... with<br />
 &#124; val s -> (*success*)<br />
 &#124; Arithmetic (); Div_by_zero () -> (*Division by zero*)<br />
 &#124; Arithmetic (); _                   -> (*Other arithmetic*)<br />
 &#124; IO _                                  -> (*Some IO stuff *)<br />
 &#124; finally _                             -> (*Don't forget to close the door*)<br />
[/sourcecode]</p>
<p>This extract introduces three keywords:</p>
<ul>
<li><code>attempt</code> is our replacement for <code>try</code></li>
<li><code>val</code> is used to pattern-match against the result of a successful evaluation</li>
<li><code>finally</code> is used to pattern-match against the final result, whether this result was obtained after a successful evaluation or after an exception was raised and handled.</li>
</ul>
<h3>Unbreaking tail-recursion</h3>
<p>The following extract is wrong:</p>
<p>[sourcecode lang='python']<br />
let line_count filename =<br />
  let rec loop file count =<br />
  try<br />
    ignore (input_line file);<br />
    loop file (count + 1)<br />
  with<br />
    End_of_file -> count<br />
  in<br />
    loop (open_file filename) 0<br />
[/sourcecode]</p>
<p align="justify">Don't get me wrong, it will compile and run. The problem is that it's not tail-recursive. In other words, it will be much slower and much more memory-consuming than if exceptions had been ignored. Why ? Because exception End_of_file may have been raised from the next call to loop, so the recursive call cannot be optimized into a non-recursive call. Of course, exceptions can't be ignored in this extract, as they are required to determine when to stop reading the file. Now, a simple transformation would make the problem go away :</p>
<p>[sourcecode lang='python']<br />
let line_count filename =<br />
  let rec loop file count =<br />
    let should_continue =<br />
    try<br />
      ignore (input_line file);<br />
      true<br />
    with End_of_file -> false<br />
  in<br />
    if should_continue then loop file (count + 1)<br />
    else                    count<br />
  in<br />
    loop (open_file filename) 0<br />
[/sourcecode]</p>
<p style="text-align:justify;">Well, the transformation is simple, but it's annoying and hard to read. What's even more annoying is that it's quite common. With Catch me if you can, we would rather write the following:</p>
<p>[sourcecode lang='python']<br />
let input_line2 x = Error.legacy input_line x</p>
<p>let line_count filename =<br />
  let rec loop file count =<br />
    attempt input_line2 file with<br />
      &#124; val _ -> loop file (count + 1)<br />
      &#124; _     -> count<br />
  in<br />
  loop (open_file filename) 0<br />
[/sourcecode]</p>
<p style="text-align:justify;">In this extract, legacy is a simple manner of wrapping an existing, one-argument, function and convert it to our new exception style. It's not quite as good as wrapping the function manually and giving it an actual exception, but it's better than nothing.</p>
<p align="justify">All in all, the resulting function line_count is shorter, easier to read, takes less memory and is also faster than the original.</p>
<h2>What about performance?</h2>
<p style="text-align:justify;">Now, that's a complex question. Short answer: there's an acceptable performance loss. False short answer: we wrote a <a href="http://www.univ-orleans.fr/lifo/Members/David.Teller/publications/ml2008.pdf">paper</a> on that subject.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Higher-Order Java Parallelism, Part 1: Parallel Strategies and the Callable Monad]]></title>
<link>http://apocalisp.wordpress.com/?p=18</link>
<pubDate>Thu, 19 Jun 2008 05:08:35 +0000</pubDate>
<dc:creator>apocalisp</dc:creator>
<guid>http://apocalisp.wordpress.com/?p=18</guid>
<description><![CDATA[Now that even budget desktop and laptop computers are shipping with multi-core processors, it&#8217;]]></description>
<content:encoded><![CDATA[<p>Now that even budget desktop and laptop computers are shipping with multi-core processors, it's more important than ever to design programs so that they can take advantage of parallel processing. If you're already writing software in <a href="http://en.wikipedia.org/wiki/Erlang_programming_language" target="_blank">Erlang</a> or <a href="http://www.macs.hw.ac.uk/~dsg/gph/" target="_blank">Parallel Haskell</a>, then lucky you. But if you're writing in Java (and are unable or unwilling to take up <a href="http://www.scala-lang.org/" target="_blank">Scala</a>), you will need to get organized.</p>
<p>Since Java 5, <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/package-summary.html" target="_blank">the JDK comes with a concurrency library</a> that makes concurrent programming a lot easier than it used to be, and the library has been improved further in Java 6. This provides some basic abstractions that take care of the nitty-gritty of thread management for us. In this short series of articles, I'm going to show how we can build on top of that library to achieve concurrent programming of a higher order. We will employ some design patterns and simple abstract building blocks from functional programming. This style of writing concurrent programs will afford us the ability to:</p>
<ul>
<li>Compose ordinary functions into concurrent programs.</li>
<li>Decouple parallel behavior from the algorithm itself.</li>
<li>Turn existing code into parallel code, without refactoring, at runtime.</li>
<li>Work with hypothetical results of concurrent computations, before they finish.</li>
</ul>
<p>We will not use any locking or explicit synchronization. Basic familiarity with the java.util.concurrent package is assumed but not required. Familiarity with <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html" target="_blank">generics</a> is highly recommended, and I recommend reading <a href="http://apocalisp.wordpress.com/2008/05/16/thrower-functor/" target="_blank">parts 1 and 2 of my Lazy Error Handling series</a> as it explains some preliminaries. Most of the source code herein is already part of the <a href="http://functionaljava.org/" target="_blank">Functional Java library</a>, and I'll use a fair bit of interfaces and classes from it, which I'll introduce as we go along.</p>
<p>When we're through, I will have demonstrated that a functional style of programming promotes code-reuse and modularity of parallel programs, above and beyond what can be achieved with the canonical object-orientated style.</p>
<p><strong>The Callable Monad</strong></p>
<p>The <em><a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/Callable.html" target="_blank">Callable</a> </em>interface is new in Java 5. It's similar to the old <em><a href="http://java.sun.com/javase/6/docs/api/java/lang/Runnable.html" target="_blank">Runnable</a> </em>interface that we all know and love, except that its <em>call() </em>method returns a result, and it may throw an <em>Exception</em>. If you followed my Lazy Error Handling articles, you will immediately notice that <em>Callable </em>is nearly identical to the <em>Thrower </em>interface described in that series, and you'll know that it is indeed a potential monad. Treating <em>Callable </em>as a monad will allow us to work with it at a higher level of abstraction, letting us compose <em>Callables</em>, chain them, and project computations into them.</p>
<p>As you may already know, we need three ingredients (and only these three) to have a monad:</p>
<ol>
<li>Type construction. This comes free with the <em>Callable </em>interface, since it takes a type parameter (i.e. it's generic).</li>
<li>A unit function. This allows us to turn any value into a <em>Callable </em>that returns that value again.</li>
<li>A binding function. This allows us to chain together <em>Callables </em>with functions, without actually calling them.</li>
</ol>
<p>Here is the unit function for <em>Callable</em> (we will refer to it as <em>unit</em> in the text to avoid ambiguity):</p>
<pre>  <span style="color:#eb7950;">public</span> <span style="color:#eb7950;">static</span> &#60;A&#62; Callable&#60;A&#62; callable(<span style="color:#eb7950;">final</span> A a) <span style="color:#339933;">{</span>
    <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">new</span> Callable&#60;A&#62;() <span style="color:#339933;">{</span>
<span style="color:#339933;">      </span><span style="color:#eb7950;">public</span><span style="color:#339933;"> A call()</span> <span style="color:#339933;">{</span>
        <span style="color:#0000ff;">return</span> a;
      <span style="color:#339933;">}</span>
    <span style="color:#339933;">}</span>;
  <span style="color:#339933;">}</span></pre>
<p>And here is its binding function:</p>
<pre>  <span style="color:#eb7950;">public</span> <span style="color:#eb7950;">static</span> &#60;A, B&#62; Callable&#60;B&#62; bind(<span style="color:#eb7950;">final</span> Callable&#60;A&#62; a, <span style="color:#eb7950;">final</span> F&#60;A, Callable&#60;B&#62;&#62; f) <span style="color:#339933;">{</span>
    <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">new</span> Callable&#60;B&#62;() <span style="color:#339933;">{</span>
<span style="color:#339933;">      </span><span style="color:#eb7950;">public</span><span style="color:#339933;"> B call()</span> <span style="color:#eb7950;">throws</span> <span style="color:#0000ff;">Exception</span> <span style="color:#339933;">{</span>
        <span style="color:#0000ff;">return</span> f.f(a.call()).call();
      <span style="color:#339933;">}</span>
    <span style="color:#339933;">}</span>;
  <span style="color:#339933;">}</span></pre>
<p>Note: <a href="http://projects.workingmouse.com/public/functionaljava/artifacts/2.7/javadoc/fj/F.html" target="_blank">The F interface</a> is from Functional Java. It represents a first-class function (a function that can be treated like any other value). <em>F&#60;A, B&#62;</em> has one method that takes an argument of type <em>A</em> and returns a value of type <em>B</em>.</p>
<p>Given the above two methods, Callable is now a monad. All monads are also functors, so we can define a <em>Callable </em>functor. What I mean by "functor" is that we can define a method to turn any existing function into a function on Callables, or, in other words, to apply any function to a value wrapped in a Callable, without actually calling it (i.e. lazily). This method is called <em>fmap</em>, and we can define it in terms of <em>bind</em>:</p>
<pre>  <span style="color:#eb7950;">public</span> <span style="color:#eb7950;">static</span> &#60;A, B&#62; F&#60;Callable&#60;A&#62;, Callable&#60;B&#62;&#62; fmap(<span style="color:#eb7950;">final</span> F&#60;A, B&#62; f) <span style="color:#339933;">{</span>
    <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">new</span> F&#60;Callable&#60;A&#62;, Callable&#60;B&#62;&#62;() <span style="color:#339933;">{</span>
<span style="color:#339933;">      </span><span style="color:#eb7950;">public</span><span style="color:#339933;"> Callable&#60;B&#62; f(</span><span style="color:#eb7950;">final</span><span style="color:#339933;"> Callable&#60;A&#62; a)</span> <span style="color:#339933;">{</span>
        <span style="color:#0000ff;">return</span> bind(a, <span style="color:#0000ff;">new</span> F&#60;A, Callable&#60;B&#62;&#62;() <span style="color:#339933;">{</span>
<span style="color:#339933;">          </span><span style="color:#eb7950;">public</span><span style="color:#339933;"> Callable&#60;B&#62; f(</span><span style="color:#eb7950;">final</span><span style="color:#339933;"> A ab)</span> <span style="color:#339933;">{</span>
            <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">new</span> Callable&#60;B&#62;() <span style="color:#339933;">{</span>
<span style="color:#339933;">              </span><span style="color:#eb7950;">public</span><span style="color:#339933;"> B call()</span> <span style="color:#339933;">{</span>
                <span style="color:#0000ff;">return</span> f.f(ab);
              <span style="color:#339933;">}</span>
            <span style="color:#339933;">}</span>;
          <span style="color:#339933;">}</span>
        <span style="color:#339933;">}</span>);
      <span style="color:#339933;">}</span>
    <span style="color:#339933;">}</span>;
  <span style="color:#339933;">}</span></pre>
<p>Useful operations on <em>Callables</em>, that the methods above allow us to implement,<em> </em>include <em>sequence</em>---which is a method of turning a list of <em>Callables </em>into a single <em>Callable </em>that returns a list---and <em>join</em>, which peels one layer of <em>Callables</em> from a <em>Callable&#60;Callable&#60;A&#62;&#62;</em> so that it becomes just <em>Callable&#60;A&#62;</em>. You will find the source code for those as part of <a href="http://functionaljava.org" target="_blank">Functional Java</a>.</p>
<p><strong>Parallel Strategies</strong></p>
<p>When working with the <em>java.util.concurrent </em>library, you normally don't work with <em>Threads </em>directly. You might instead implement <em>Callable&#60;A&#62;</em> and submit instances of your implementation to an <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html" target="_blank"><em>ExecutorService</em></a>, which yields values of type <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/Future.html" target="_blank"><em>Future&#60;A&#62;</em></a> which represents a running computation that yields an <em>A</em>. <em>Future</em> has a method called <em>get()</em> that returns the result as soon as it's ready. This is a great improvement over managing threads and Runnables ourselves, but it still ties our hands somewhat to the <em>ExecutorService</em>, and encourages tight coupling of our code to the parallelisation library.</p>
<p>Inspired by <a href="http://www.macs.hw.ac.uk/~dsg/gph/papers/html/Strategies/strategies.html" target="_blank">Haskell's "Parallel Strategies"</a>, let's instead work with parallelisation in the abstract. For what is <em>ExecutorService</em>, really? It's a method of turning <em>Callables </em>into <em>Futures</em>. That means it's a kind of function, so we can abstract from it, using a function type: <em>F&#60;Callable&#60;A&#62;, Future&#60;A&#62;&#62;</em>. Such a function can then be backed by an <em>ExecutorService</em>, or by something else entirely, such as a load-balancing facility that serializes <em>Callables </em>to be executed on remote servers.</p>
<p>We will use a new class, <em>Strategy&#60;A&#62;</em>, that allows us to effectively separate parallelism from the algorithm itself:</p>
<pre>  <span style="color:#eb7950;">public</span> <span style="color:#eb7950;">final</span> <span style="color:#eb7950;">class</span> Strategy&#60;A&#62; <span style="color:#339933;">{</span>

    <span style="color:#eb7950;">private</span> F&#60;Callable&#60;A&#62;, Future&#60;A&#62;&#62; f;

<span style="color:#339933;">    </span><span style="color:#eb7950;">private</span><span style="color:#339933;"> Strategy(</span><span style="color:#eb7950;">final</span><span style="color:#339933;"> F&#60;Callable&#60;A&#62;, Future&#60;A&#62;&#62; f)</span> <span style="color:#339933;">{</span>
      <span style="color:#eb7950;">this</span>.f = f;
    <span style="color:#339933;">}</span>

    <span style="color:#eb7950;">public</span> F&#60;Callable&#60;A&#62;, Future&#60;A&#62;&#62; f() <span style="color:#339933;">{</span>
      <span style="color:#0000ff;">return</span> f;
    <span style="color:#339933;">}</span>

    <span style="color:#eb7950;">public</span> <span style="color:#eb7950;">static</span> &#60;A&#62; Strategy&#60;A&#62; strategy(<span style="color:#eb7950;">final</span> F&#60;Callable&#60;A&#62;, Future&#60;A&#62;&#62; f) <span style="color:#339933;">{</span>
      <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">new</span> Strategy&#60;A&#62;(f);
    <span style="color:#339933;">}</span>

  <span style="color:#339933;">}</span></pre>
<p>We'll add a couple of static functions to create simple strategies:</p>
<pre>  <span style="color:#eb7950;">public</span> <span style="color:#eb7950;">static</span> &#60;A&#62; Strategy&#60;A&#62; simpleThreadStrategy() <span style="color:#339933;">{</span>
    <span style="color:#0000ff;">return</span> strategy(<span style="color:#0000ff;">new</span> F&#60;Callable&#60;A&#62;, Future&#60;A&#62;&#62;() <span style="color:#339933;">{</span>
<span style="color:#339933;">      </span><span style="color:#eb7950;">public</span><span style="color:#339933;"> Future&#60;A&#62; f(</span><span style="color:#eb7950;">final</span><span style="color:#339933;"> Callable&#60;A&#62; p)</span> <span style="color:#339933;">{</span>
        <span style="color:#eb7950;">final</span> <span style="background-color:#ededed;"><span style="color:#333333;">FutureTask</span></span>&#60;A&#62; t = <span style="color:#0000ff;">new</span> <span style="background-color:#ededed;"><span style="color:#333333;">FutureTask</span></span>&#60;A&#62;(p);
        <span style="color:#0000ff;">new</span> <span style="background-color:#ededed;"><span style="color:#333333;">Thread</span></span>(t).start();
        <span style="color:#0000ff;">return</span> t;
      <span style="color:#339933;">}</span>
    <span style="color:#339933;">}</span>);
  <span style="color:#339933;">}</span>

  <span style="color:#eb7950;">public</span> <span style="color:#eb7950;">static</span> &#60;A&#62; Strategy&#60;A&#62; executorStrategy(<span style="color:#eb7950;">final</span> ExecutorService s) <span style="color:#339933;">{</span>
    <span style="color:#0000ff;">return</span> strategy(<span style="color:#0000ff;">new</span> F&#60;Callable&#60;A&#62;, Future&#60;A&#62;&#62;() <span style="color:#339933;">{</span>
<span style="color:#339933;">      </span><span style="color:#eb7950;">public</span><span style="color:#339933;"> Future&#60;A&#62; f(</span><span style="color:#eb7950;">final</span><span style="color:#339933;"> Callable&#60;A&#62; p)</span> <span style="color:#339933;">{</span>
        <span style="color:#0000ff;">return</span> s.submit(p);
      <span style="color:#339933;">}</span>
    <span style="color:#339933;">}</span>);
  <span style="color:#339933;">}</span></pre>
<p>One of the neat things that working with <em>Strategies </em>as functions allows us to do is use the <em>Callable </em>monad to compose them with existing functions. Any function can be lifted into the <em>Callable </em>monad using <em>fmap</em>, and then composed with a <em>Strategy </em>to yield a concurrent function. Moreover, we can use <em>Strategies</em> to convert existing functions to concurrent functions. The following method on <em>Strategy</em> will take any function and return the equivalent function that executes concurrently. Calling such a function will give you a Future value from which you can get the computed result whenever it's ready.</p>
<pre>  <span style="color:#eb7950;">public</span> &#60;B&#62; F&#60;B, Future&#60;A&#62;&#62; lift(<span style="color:#eb7950;">final</span> F&#60;B, A&#62; f) <span style="color:#339933;">{</span>
    <span style="color:#eb7950;">final</span> Strategy&#60;A&#62; self = <span style="color:#eb7950;">this</span>;
    <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">new</span> F&#60;B, Future&#60;A&#62;&#62;() <span style="color:#339933;">{</span>
<span style="color:#339933;">      </span><span style="color:#eb7950;">public</span><span style="color:#339933;"> Future&#60;A&#62; f(</span><span style="color:#eb7950;">final</span><span style="color:#339933;"> B b)</span> <span style="color:#339933;">{</span>
        <span style="color:#0000ff;">return</span> self.f().f(<span style="color:#0000ff;">new</span> Callable&#60;A&#62;() <span style="color:#339933;">{</span>
<span style="color:#339933;">          </span><span style="color:#eb7950;">public</span><span style="color:#339933;"> A call()</span> <span style="color:#339933;">{</span>
            <span style="color:#0000ff;">return</span> f.f(b);
          <span style="color:#339933;">}</span>
        <span style="color:#339933;">}</span>);
      <span style="color:#339933;">}</span>
    <span style="color:#339933;">}</span>;
  <span style="color:#339933;">}</span></pre>
<p>Alert readers will note that <em>lift</em> represents the <a href="http://sigfpe.blogspot.com/2006/06/monads-kleisli-arrows-comonads-and.html" target="_blank">Kleisli arrow</a> for the <em>Future </em>monad. As for most monads, this arrow is a very useful kind of thing (see <a href="http://apocalisp.wordpress.com/2008/05/22/thrower-is-a-monad/" target="_blank">Lazy Error Handling, Part 2</a>). In the <em>Future </em>monad, the Kleisli arrow provides parallel function application. If you already have a function <em>f,</em> then calling <em>lift(f).f(x)</em> will apply that function to <em>x</em> while simultaneously continuing with the next statement in the current program.</p>
<p><strong>Lazy Futures</strong></p>
<p>For functions involving <em>Futures</em>, we generally always want to have the Future type in the codomain (on the right-hand side, in the return type). If you think about it, you'll see that functions that take <em>Futures </em>in their arguments won't be able to do much without blocking on <em>Future.get()</em>. However, that doesn't mean we can't compose <em>Future</em>-valued functions together. It just means that we can only compose two of them together in such a way that we either wait for the first <em>Future </em>to obtain a value before firing off the second one, or we have to spark a new thread that does nothing but wait on the first <em>Future</em>. We're much better off composing <em>Callables</em> and then turning those into <em>Futures </em>as needed. In fact, we might want to wrap values of type <em>Future&#60;A&#62;</em> inside of a <em>Callable&#60;A&#62;</em> again so that we can manipulate their return values <strong>while they are running</strong>:</p>
<pre>  <span style="color:#eb7950;">public</span> <span style="color:#eb7950;">static</span> &#60;A&#62; Callable&#60;A&#62; obtain(<span style="color:#eb7950;">final</span> Future&#60;A&#62; x) <span style="color:#339933;">{</span>
    <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">new</span> Callable&#60;A&#62;() <span style="color:#339933;">{</span>
<span style="color:#339933;">      </span><span style="color:#eb7950;">public</span><span style="color:#339933;"> A call()</span> <span style="color:#eb7950;">throws</span> <span style="color:#0000ff;">Exception</span> <span style="color:#339933;">{</span>
        <span style="color:#0000ff;">return</span> x.get();
      <span style="color:#339933;">}</span>
    <span style="color:#339933;">}</span>;
  <span style="color:#339933;">}</span></pre>
<p>And this takes us full circle back into the Callable monad, where we can compose computations, bind them to functions and map functions over them, all lazily. Which means: without actually asking what their values are until we absolutely need to know.</p>
<p>So we have accomplished what we set out to do in this first part of the series. We've written a <em>Callable </em>monad that lets us compose existing code into concurrent programs. We've implemented parallel strategies to run those programs in parallel, without regard to the actual parallelisation implementation. We have a Kleisli arrow that lets us run ordinary functions concurrently with each other, and finally we have a way of taking concurrently running  computations back into the Callable monad. Not bad for a day's work.</p>
<p>In the next part of this series, we will employ what we've built here to develop some higher-order parallel functions, including a parallel list functor. I hope you join me.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Wrap-up: mergesort in haskell]]></title>
<link>http://muharem.wordpress.com/?p=45</link>
<pubDate>Tue, 10 Jun 2008 18:42:30 +0000</pubDate>
<dc:creator>muharem</dc:creator>
<guid>http://muharem.wordpress.com/?p=45</guid>
<description><![CDATA[I have to admit that I didn’t fully understand the apfelmus example code. Nevertheless, I made an ]]></description>
<content:encoded><![CDATA[<p>I have to admit that I didn’t fully understand the <a href="http://article.gmane.org/gmane.comp.lang.haskell.general/15010">apfelmus example code</a>. Nevertheless, I made an effort to address both of <a href="http://muharem.wordpress.com/2008/06/05/finger-exercises-in-haskell/#comment-5117">his criticisms</a>:</p>
<ol>
<li>The merge() function does not use an accumulator argument any more and is indeed much simpler now.</li>
<li>The recursive <code>mergesort_</code> function now does not use the haskell list <code>length</code> operator any more. Instead, the length of the list to be sorted is passed down the recursive chain.</li>
</ol>
<p>Please see the <a href="http://hrnjad.net/src/s/optimized-mergesort.hs.html">optimised mergesort implementation</a> for details.</p>
<p>These improvements reduced the RAM utilisation and improved the run-time performance by another 20% respectively.</p>
<p>Nothing to scoff at, eh?</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Haskell byte strings to the rescue!]]></title>
<link>http://muharem.wordpress.com/?p=44</link>
<pubDate>Fri, 06 Jun 2008 08:17:49 +0000</pubDate>
<dc:creator>muharem</dc:creator>
<guid>http://muharem.wordpress.com/?p=44</guid>
<description><![CDATA[After my (naive) mergesort implementation from yesterday used around 730 MB of RAM to sort a (26 MB)]]></description>
<content:encoded><![CDATA[<p>After my (naive) mergesort <a href="http://muharem.wordpress.com/2008/06/05/finger-exercises-in-haskell/">implementation from yesterday</a> used around 730 MB of RAM to sort a (26 MB) file containing approx. 400,000 strings I consulted the good folks on the <code>#haskell</code> IRC channel.</p>
<p>Their advice was to use <a href="http://www.haskell.org/ghc/docs/latest/html/libraries/bytestring/Data-ByteString.html">byte strings</a> as opposed to normal strings since the former perform much better.</p>
<p>I tried that and observed that the RAM utilisation and run-time went down by approximately 85% !</p>
<p>The reduced RAM utilisation was attributed to the more efficient byte strings and the improved run-time performance to the reduced garbage collection overhead respectively.</p>
<p>The <a href="http://hrnjad.net/src/s/bytestring.diff.html">difference</a> between the source files (<a href="http://hrnjad.net/src/s/byte-mergesort.hs.html">mergesort.hs</a>, <a href="http://hrnjad.net/src/s/byte-Scaffolding.hs.html">Scaffolding.hs</a>) is minimal and switching over to byte strings was facilitated by the fact that they expose the same interface as normal strings.</p>
<p>Nice!</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Finger exercises in haskell]]></title>
<link>http://muharem.wordpress.com/?p=43</link>
<pubDate>Thu, 05 Jun 2008 07:49:30 +0000</pubDate>
<dc:creator>muharem</dc:creator>
<guid>http://muharem.wordpress.com/?p=43</guid>
<description><![CDATA[I have been reading about haskell for a while now and felt that it&#8217;s time to &#8220;get my han]]></description>
<content:encoded><![CDATA[<p>I have been reading about <a href="http://www.haskell.org/">haskell</a> for a while now and felt that it's time to "get my hands dirty" by (re-)implementing some of the well known algorithms in computer science. For my first exercise I chose <a href="http://en.wikipedia.org/wiki/Merge_sort">merge sort</a>.</p>
<p>The <a href="http://hrnjad.net/src/s/mergesort.hs.html">resulting code</a> (sans command line parameter handling, <a href="http://hrnjad.net/src/s/Scaffolding.hs.html">auxiliary I/O functions</a> etc.) is quite neat and was written in little time. Haskell is very expressive and its attractiveness immediately obvious when formulating pseudo-mathematical problem solutions.</p>
<pre> <span style="color:#7f7f7f;"> 1 </span><span>module</span> Main(main) <span>where</span>
 <span style="color:#7f7f7f;"> 2 </span>
 <span style="color:#7f7f7f;"> 3 </span><span style="color:#cd00cd;">import</span> <span style="color:#cd00cd;">qualified</span> IO
 <span style="color:#7f7f7f;"> 4 </span><span style="color:#cd00cd;">import</span> System(getArgs)
 <span style="color:#7f7f7f;"> 5 </span><span style="color:#cd00cd;">import</span> Monad(mapM_)
 <span style="color:#7f7f7f;"> 6 </span><span style="color:#cd00cd;">import</span> <span style="color:#cd00cd;">qualified</span> Scaffolding
 <span style="color:#7f7f7f;"> 7 </span>
 <span style="color:#7f7f7f;"> 8 </span>mergesort l <span style="font-weight:bold;color:#00008b;">=</span>
 <span style="color:#7f7f7f;"> 9 </span>    <span style="font-weight:bold;color:#00008b;">if</span> (length l) <span style="font-weight:bold;color:#00008b;">&#60;=</span> <span style="color:#008b00;">1</span> <span style="font-weight:bold;color:#00008b;">then</span> l <span style="color:#7f7f7f;">-- The list is already sorted.</span>
 <span style="color:#7f7f7f;">10 </span>    <span style="font-weight:bold;color:#00008b;">else</span> <span style="color:#7f7f7f;">-- Split the list into two halves and sort these.</span>
 <span style="color:#7f7f7f;">11 </span>        merge (mergesort lpart) (mergesort rpart) []
 <span style="color:#7f7f7f;">12 </span>        <span>where</span> llen_half <span style="font-weight:bold;color:#00008b;">=</span> (length l) <span style="font-weight:bold;color:#00008b;">`div`</span> <span style="color:#008b00;">2</span>
 <span style="color:#7f7f7f;">13 </span>              (lpart, rpart) <span style="font-weight:bold;color:#00008b;">=</span> splitAt llen_half l
 <span style="color:#7f7f7f;">14 </span>
 <span style="color:#7f7f7f;">15 </span><span style="color:#7f7f7f;">-- Case #1: the right list is empty; just append the left list to the</span>
 <span style="color:#7f7f7f;">16 </span><span style="color:#7f7f7f;">-- accumulator. The latter is reversed because we were prepending</span>
 <span style="color:#7f7f7f;">17 </span><span style="color:#7f7f7f;">-- to it in case #3.</span>
 <span style="color:#7f7f7f;">18 </span>merge lpart [] acc <span style="font-weight:bold;color:#00008b;">=</span> (reverse acc) <span style="font-weight:bold;color:#00008b;">++</span> lpart
 <span style="color:#7f7f7f;">19 </span>
 <span style="color:#7f7f7f;">20 </span><span style="color:#7f7f7f;">-- Case #2: the left list is empty; just append the right list to the</span>
 <span style="color:#7f7f7f;">21 </span><span style="color:#7f7f7f;">-- (reversed) accumulator list.</span>
 <span style="color:#7f7f7f;">22 </span>merge [] rpart acc <span style="font-weight:bold;color:#00008b;">=</span> (reverse acc) <span style="font-weight:bold;color:#00008b;">++</span> rpart
 <span style="color:#7f7f7f;">23 </span>
 <span style="color:#7f7f7f;">24 </span><span style="color:#7f7f7f;">-- Case #3: neither of the left/right lists to be merged is empty;</span>
 <span style="color:#7f7f7f;">25 </span><span style="color:#7f7f7f;">-- prepend the lesser head element to the accumulator list.</span>
 <span style="color:#7f7f7f;">26 </span>merge (l<span style="font-weight:bold;color:#00008b;">:</span>ls) (r<span style="font-weight:bold;color:#00008b;">:</span>rs) acc <span style="font-weight:bold;color:#00008b;">=</span>
 <span style="color:#7f7f7f;">27 </span>    <span style="font-weight:bold;color:#00008b;">if</span> l <span style="font-weight:bold;color:#00008b;">&#60;=</span> r <span style="font-weight:bold;color:#00008b;">then</span> merge ls (r<span style="font-weight:bold;color:#00008b;">:</span>rs) (l<span style="font-weight:bold;color:#00008b;">:</span>acc)
 <span style="color:#7f7f7f;">28 </span>    <span style="font-weight:bold;color:#00008b;">else</span> merge (l<span style="font-weight:bold;color:#00008b;">:</span>ls) rs (r<span style="font-weight:bold;color:#00008b;">:</span>acc)
 <span style="color:#7f7f7f;">29 </span>
 <span style="color:#7f7f7f;">30 </span><span style="color:#7f7f7f;">-- The main method, handles command line arguments, input and output.</span>
 <span style="color:#7f7f7f;">31 </span>main <span style="font-weight:bold;color:#00008b;">=</span> <span style="font-weight:bold;color:#00008b;">do</span>
 <span style="color:#7f7f7f;">32 </span>    args <span style="font-weight:bold;color:#00008b;">&#60;-</span> getArgs
 <span style="color:#7f7f7f;">33 </span>    fileh <span style="font-weight:bold;color:#00008b;">&#60;-</span> <span style="font-weight:bold;color:#00008b;">case</span> head args <span style="font-weight:bold;color:#00008b;">of</span>
 <span style="color:#7f7f7f;">34 </span>                <span style="color:#7f7f7f;">-- The text to be sorted is to be read from stdin.</span>
 <span style="color:#7f7f7f;">35 </span>                <span style="color:#008b00;">"-"</span> <span style="font-weight:bold;color:#00008b;">-&#62;</span> <span style="font-weight:bold;color:#00008b;">do</span> return (Just IO.stdin)
 <span style="color:#7f7f7f;">36 </span>                <span style="color:#7f7f7f;">-- The text to be sorted is to be read from the file</span>
 <span style="color:#7f7f7f;">37 </span>                <span style="color:#7f7f7f;">-- specified.</span>
 <span style="color:#7f7f7f;">38 </span>                <span style="color:#008b00;">"-f"</span> <span style="font-weight:bold;color:#00008b;">-&#62;</span> <span style="font-weight:bold;color:#00008b;">do</span> Scaffolding.openFile (head (tail args))
 <span style="color:#7f7f7f;">39 </span>                <span style="color:#7f7f7f;">-- Just sort the command line parameters.</span>
 <span style="color:#7f7f7f;">40 </span>                _ <span style="font-weight:bold;color:#00008b;">-&#62;</span> <span style="font-weight:bold;color:#00008b;">do</span> <span style="font-weight:bold;color:#00008b;">let</span> sorted_args <span style="font-weight:bold;color:#00008b;">=</span> mergesort args
 <span style="color:#7f7f7f;">41 </span>                        IO.putStrLn (<span style="color:#008b00;">"mergesort("</span> <span style="font-weight:bold;color:#00008b;">++</span> show args <span style="font-weight:bold;color:#00008b;">++</span>
 <span style="color:#7f7f7f;">42 </span>                                     <span style="color:#008b00;">") = "</span> <span style="font-weight:bold;color:#00008b;">++</span> show sorted_args)
 <span style="color:#7f7f7f;">43 </span>                        return Nothing
 <span style="color:#7f7f7f;">44 </span>    <span style="font-weight:bold;color:#00008b;">case</span> fileh <span style="font-weight:bold;color:#00008b;">of</span>
 <span style="color:#7f7f7f;">45 </span>        <span style="color:#7f7f7f;">-- Read text from file handle, sort it and print to stdout.</span>
 <span style="color:#7f7f7f;">46 </span>        Just fileh <span style="font-weight:bold;color:#00008b;">-&#62;</span> <span style="font-weight:bold;color:#00008b;">do</span> text_to_sort <span style="font-weight:bold;color:#00008b;">&#60;-</span> Scaffolding.readLines fileh []
 <span style="color:#7f7f7f;">47 </span>                         mapM_ IO.putStrLn (mergesort text_to_sort)
 <span style="color:#7f7f7f;">48 </span>        <span style="color:#7f7f7f;">-- We failed to open the file specified (if any).</span>
 <span style="color:#7f7f7f;">49 </span>        Nothing <span style="font-weight:bold;color:#00008b;">-&#62;</span> <span style="font-weight:bold;color:#00008b;">do</span> return ()</pre>
<p>I also liked the fact that the <a href="http://www.haskell.org/ghc/docs/latest/html/libraries/">haskell standard library</a> is rich and nicely documented.</p>
<p>Just to get an idea of how my naive <code>mergesort</code> implementation performs I created a file listing all the files on my Dell D630 laptop running <a href="http://www.ubuntu.com">Hardy Heron</a> (please ignore the recursive nature of this problem :-) ).</p>
<pre> <span style="color:#7f7f7f;">1 </span>u804: haskell $ <span style="font-weight:bold;">ghc --version</span>
 <span style="color:#7f7f7f;">2 </span>The Glorious Glasgow Haskell Compilation System, version 6.8.2
 <span style="color:#7f7f7f;">3 </span>u804: haskell $ <span style="font-weight:bold;">ls -l all-files.txt</span>
 <span style="color:#7f7f7f;">4 </span>-rw-r--r-- 1 mhr mhr 26245382 2008-05-31 17:18 all-files.txt
 <span style="color:#7f7f7f;">5 </span>u804: haskell $ <span style="font-weight:bold;">wc -l all-files.txt</span>
 <span style="color:#7f7f7f;">6 </span>399754 all-files.txt
 <span style="color:#7f7f7f;">7 </span>u804: haskell $ <span style="font-weight:bold;">uname -a</span>
 <span style="color:#7f7f7f;">8 </span>Linux u804 2.6.24-18-generic #1 SMP Wed May 28 20:27:26 UTC 2008 i686 GNU/Linux</pre>
<p>I then let loose the compiled haskell binary on that file (<code>all-files.txt</code>) and compared how it performed against <code>/usr/bin/sort</code>.</p>
<pre> <span style="color:#7f7f7f;"> 1 </span>u804: haskell $ <span style="font-weight:bold;">time ./mergesort -f all-files.txt &#62;/dev/null</span>
 <span style="color:#7f7f7f;"> 2 </span>
 <span style="color:#7f7f7f;"> 3 </span>real    0m12.994s
 <span style="color:#7f7f7f;"> 4 </span>user    0m12.349s
 <span style="color:#7f7f7f;"> 5 </span>sys 0m0.632s
 <span style="color:#7f7f7f;"> 6 </span>u804: haskell $ <span style="font-weight:bold;">time sort all-files.txt &#62;/dev/null</span>
 <span style="color:#7f7f7f;"> 7 </span>
 <span style="color:#7f7f7f;"> 8 </span>real    0m10.675s
 <span style="color:#7f7f7f;"> 9 </span>user    0m10.613s
 <span style="color:#7f7f7f;">10 </span>sys 0m0.052s
 <span style="color:#7f7f7f;">11 </span>u804: haskell $ <span style="font-weight:bold;">time sort all-files.txt &#62;/dev/null</span></pre>
<p>The difference in performance was moderate (22%) given that I did not tune the haskell implementation in any way.</p>
<p>However, I gasped when I observed the RAM utilisation while the haskell program  was running: it used 726 MB of RAM!</p>
<p>Compare this to 34 MB that were used by the standard <code>sort</code> program.</p>
<p>I guess it's time to get acquainted with <a href="http://www.haskell.org/ghc/docs/latest/html/users_guide/profiling.html"><code>ghc -prof</code></a> and friends :-)</p>
<p>Last but not least I'd like to point to a great haskell resource, the <a href="http://book.realworldhaskell.org/beta/index.html">Real World Haskell</a> beta book.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Lazy Error Handling in Java, Part 3: Throwing Away Throws]]></title>
<link>http://apocalisp.wordpress.com/?p=15</link>
<pubDate>Wed, 04 Jun 2008 20:29:32 +0000</pubDate>
<dc:creator>apocalisp</dc:creator>
<guid>http://apocalisp.wordpress.com/?p=15</guid>
<description><![CDATA[In parts 1 and 2, I covered how we could create first-class functions in Java that declare, in their]]></description>
<content:encoded><![CDATA[<p><a href="http://apocalisp.wordpress.com/2008/05/16/thrower-functor/" target="_blank">In parts 1 and 2</a>, I covered how we could create first-class functions in Java that declare, in their types, the exceptions they might throw. I talked about exploiting a functor to lift any existing function so that it carries exception information with it, and how to compose functions of that kind by using a monad. In this third and last installment, we're going to fully abandon checked exceptions and embrace the functional style of handling errors.</p>
<p>First, let's examine what exceptions really are. During the evaluation of some expression (some function), unexpected conditions or data are encountered, with which it is undefined how to proceed. That is to say, for some inputs, the result of the computation is undefined. For example, when a parseInt function encounters a character that isn't a digit (or a minus sign), what do we do? Well, we don't know exactly, so we need some way to indicate failure. It would be invalid to return an integer. One could return null, <a href="http://apocalisp.wordpress.com/2008/05/03/null-vs-pure-reason/" target="_blank">but that isn't exactly reliable, nor correct,</a> and well, it would be lying since the type signature promises an integer.</p>
<p>So far, I've shown how we can use a Thrower monad to indicate that a computation can error. But the Thrower monad doesn't do anything except wrap Java's existing exception handling with a datastructure. And what do you think Java's existing error handling is? <a href="http://blog.tmorris.net/maybe-monad-in-java/" target="_blank">It's a monad</a>. <a href="http://citeseer.ist.psu.edu/656853.html" target="_blank">No, really, it is</a>. In fact, Java is one big monad with bells on.</p>
<p>Note that <em>throws</em> changes the type of a method so that it may throw exceptions. Sound familiar? That's what Thrower does (<a href="http://apocalisp.wordpress.com/2008/05/16/thrower-functor/" target="_blank">see part 1</a>). Java's <em>throws</em> keyword is the Kleisli arrow (<a href="http://apocalisp.wordpress.com/2008/05/22/thrower-is-a-monad/" target="_blank">see part 2</a>) for Java's exceptions functor. Binding is done with a combination of <em>try</em> and a Java keyword called "<strong>;</strong>" which I'm sure you use all the time without even batting an eye. You can then think of <em>catch</em> as a function that takes a monadic value and "extracts" from it, performing case analysis on the result.</p>
<p>Why did we need Thrower then? The difference is that <em>throws</em> needs to be hard-coded at method definition time, while our Kleisli arrow, which we called <em>Partial</em>, transforms function values "at runtime".</p>
<p><strong>Returning Errors<br />
</strong></p>
<p>We now find that we can take this idea further. We don't actually need the <em>throws</em> monad at all, and hence, we don't need <em>Thrower</em> either. Don't get me wrong. I like the Trower monad. I use the Thrower monad in production. But let's explore what we can do to approach a more functional style of error handling, just for grins.</p>
<p>Instead of throwing Exceptions, we can just collapse error types into the return type. We'll use a monad called <em>Either</em>, which looks very similar to <em>Thrower </em>except that errors are returned, not thrown. The <a href="http://functionaljava.org" target="_blank">Functional Java</a> library luckily has <a href="http://projects.workingmouse.com/public/functionaljava/artifacts/2.6/javadoc/fj/data/Either.html" target="_blank"><em>Either </em>already defined</a>:</p>
<pre style="background:#242424;color:#f6f3e8;"><span style="color:#cae682;">
  public</span> <span style="color:#cae682;">abstract</span> <span style="color:#cae682;">class</span> Either&#60;A, B&#62;<span>
</span><span>
</span></pre>
<p><em>Either </em>is the disjoint union of two types. A value of type <em>Either&#60;A, B&#62;</em> simply wraps a value of either type <em>A</em> or type <em>B</em>. The <em>Either </em>class comes with two static data constructors:</p>
<pre style="background:#242424;color:#f6f3e8;"><span style="color:#cae682;">
  public</span> <span style="color:#cae682;">static</span> &#60;A, B&#62; Either&#60;A, B&#62; left(<span style="color:#cae682;">final</span> A a)

<span style="color:#cae682;">  public</span> <span style="color:#cae682;">static</span> &#60;A, B&#62; Either&#60;A, B&#62; right(<span style="color:#cae682;">final</span> B b)<span>
</span><span>
</span></pre>
<p>We'll use the standard convention that <em>left</em> values represent failure, and that <em>right </em>values represent success.</p>
<p>Let's see how we might use this data type for error handling. It's really quite straightforward. The following declares the return type of <em>parseInt </em>to be either an <em>Exception </em>or an <em>Integer</em> (the left value can actually be any type, but... baby steps).</p>
<pre style="background:#242424;color:#f6f3e8;"><span style="color:#cae682;">
  public</span> Either&#60;<span style="color:#8ac6f2;">Exception</span>, <span style="color:#e5786d;">Integer</span>&#62; parseInt(<span style="color:#e5786d;">String</span> s);<span>
</span><span>
</span></pre>
<p>Oh, but wait. We've lost the laziness. Functional Java's <em>Either</em>, by itself, is not lazy like <em>Thrower </em>is. If we do want laziness, we have to wrap the computation in a closure. For example, we can use <em>fj.P1</em>, which is just a generic interface with one method <em>_1()</em> which takes no arguments.</p>
<pre style="background:#242424;color:#f6f3e8;"><span style="color:#cae682;">
  public</span> P1&#60;Either&#60;<span style="color:#8ac6f2;">Exception</span>, <span style="color:#e5786d;">Integer</span>&#62;&#62; parseInt(<span style="color:#e5786d;">String</span> s);<span>
</span><span>
</span></pre>
<p>That's better. Raising errors is done by returning a <em>left </em>value:</p>
<pre style="background:#242424;color:#f6f3e8;"><span style="color:#8ac6f2;">
  return</span> new P1&#60;Either&#60;<span style="color:#8ac6f2;">Exception</span>, <span style="color:#e5786d;">Integer</span>&#62;&#62;() <span style="color:#cae682;">{</span>
    <span style="color:#cae682;">public</span> Either&#60;<span style="color:#8ac6f2;">Exception</span>, <span style="color:#e5786d;">Integer</span>&#62; _1() <span style="color:#cae682;">{</span>
      <span style="color:#8ac6f2;">return</span> Either.left(<span style="color:#8ac6f2;">new</span> <span style="color:#8ac6f2;">Exception</span>(<span style="color:#95e454;"><em>"You broke it!"</em></span>));
<span><span><span><span><span><span><span><span style="color:#cae682;">    }</span></span></span></span></span></span></span></span>
<span><span style="color:#cae682;">  }</span></span><span>;  </span>
<span>
</span></pre>
<p>Sometimes you're able to call functions that might fail, recovering with a default value:</p>
<pre style="background:#242424;color:#f6f3e8;"><span>
</span>  P1&#60;Either&#60;<span style="color:#8ac6f2;">Exception</span>, <span style="color:#e5786d;">Integer</span>&#62;&#62; a = parseInt(s);
<span style="color:#cae682;">  int</span> addFive = (a._1().isLeft() ? <span style="color:#e5786d;">0</span> : a._1().right().value()) + <span style="color:#e5786d;">5</span>;<span>
</span><span>
</span></pre>
<p>Other times, you will be catching exceptions thrown by other people's code and converting them to <em>Either:</em></p>
<pre style="background:#242424;color:#f6f3e8;"><span style="color:#cae682;">
  public</span> <span style="color:#cae682;">static</span> P1&#60;Either&#60;<span style="color:#8ac6f2;">Exception</span>, <span style="color:#e5786d;">Double</span>&#62;&#62; divide(<span style="color:#cae682;">double</span> x, <span style="color:#cae682;">double</span> y) <span style="color:#cae682;">{</span>
<span style="color:#8ac6f2;">    return</span> new P1&#60;Either&#60;<span style="color:#8ac6f2;">Exception</span>, <span style="color:#e5786d;">Double</span>&#62;&#62;() <span style="color:#cae682;">{</span>
<span style="color:#cae682;">      public</span> Either&#60;<span style="color:#8ac6f2;">Exception</span>, <span style="color:#e5786d;">Double</span>&#62; _1()
  <span style="color:#8ac6f2;">      try</span> <span style="color:#cae682;">{</span>
    <span style="color:#8ac6f2;">      return</span> Either.right(x / y);
    <span style="color:#cae682;">    }</span> <span style="color:#8ac6f2;">catch</span> (<span style="color:#8ac6f2;">Exception</span> e) <span style="color:#cae682;">{</span>
      <span style="color:#8ac6f2;">    return</span> Either.left(e);
  <span style="color:#cae682;">      }</span>
<span><span style="color:#cae682;">      }</span></span>
<span style="color:#cae682;">    };</span>
<span style="color:#cae682;">  }</span><span>
</span><span>
</span></pre>
<p>An error is sent to the caller simply by returning it. In the example below, the parse errors are explicitly caught and re-raised, while any errors raised by the <em>divide </em>method are implicitly returned.</p>
<pre style="background:#242424;color:#f6f3e8;"><span style="color:#cae682;">
  public</span> <span style="color:#cae682;">static</span> P1&#60;Either&#60;<span style="color:#8ac6f2;">Exception</span>, <span style="color:#e5786d;">Double</span>&#62;&#62; parseAndDivide(<span style="color:#e5786d;">String</span> sx, <span style="color:#e5786d;">String</span> sy) <span style="color:#cae682;">{</span>
  <span style="color:#cae682;">  final</span> P1&#60;Either&#60;<span style="color:#8ac6f2;">Exception</span>, <span style="color:#e5786d;">Integer</span>&#62;&#62; x, y;
    x = parseInt(sx); y = parseInt(sy);
    <span style="color:#8ac6f2;">return</span> <span style="color:#8ac6f2;">new </span>P1&#60;Either&#60;<span style="color:#8ac6f2;">Exception</span>, <span style="color:#e5786d;">Double</span>&#62;&#62;() <span><span style="color:#cae682;">{</span></span>
<span style="color:#cae682;">      public</span> Either&#60;<span style="color:#8ac6f2;">Exception</span>, <span style="color:#e5786d;">Double</span>&#62; _1()<span><span style="color:#cae682;"> {</span></span>
    <span style="color:#8ac6f2;">    if</span> (x.isLeft() &#124;&#124; y.isLeft()) <span style="color:#cae682;">{</span>
      <span style="color:#8ac6f2;">    return</span> Either.left(x.isLeft() ? x.left().value() : y.left().value());
 <span><span style="color:#cae682;">       }</span></span>
        <span style="color:#8ac6f2;">return</span> divide(x.right().value(), y.right().value());
<span><span style="color:#cae682;">      }
</span></span><span><span style="color:#cae682;">    };</span></span>
<span style="color:#cae682;">  }</span><span>
</span><span>
</span></pre>
<p><em>Either </em>is a monad, so we can lift existing functions into it, compose Eithers, sequence them, just like we did with Throwers. Here I'm taking an existing sine function and reusing it for values of type <em>Either&#60;Exception, Double&#62;:</em></p>
<pre style="background:#242424;color:#f6f3e8;"><span>
</span>  F&#60;<span style="color:#e5786d;">Double</span>, <span style="color:#e5786d;">Double</span>&#62; sin = <span style="color:#8ac6f2;">new</span> F&#60;<span style="color:#e5786d;">Double</span>, <span style="color:#e5786d;">Double</span>&#62;() <span style="color:#cae682;">{</span>
<span style="color:#cae682;">  </span><span style="color:#cae682;">  public</span><span style="color:#cae682;"> </span><span style="color:#e5786d;">Double</span><span style="color:#cae682;"> f(</span><span style="color:#cae682;">final</span><span style="color:#cae682;"> </span><span style="color:#e5786d;">Double</span><span style="color:#cae682;"> a)</span> <span style="color:#cae682;">{</span>
    <span style="color:#8ac6f2;">  return</span> <span style="color:#e5786d;">Math</span>.sin(a);
    <span style="color:#cae682;">}</span>;<span style="color:#cae682;">}</span>

  P1&#60;Either&#60;<span style="color:#8ac6f2;">Exception</span>, <span style="color:#e5786d;">Double</span>&#62;&#62; z =
    divide(x, y).map(Either.rightMap_().f(sin));<span>
</span><span>
</span></pre>
<p>If you need to work with more than one kind of error at a time, you can. Simply nest them on the right, like so: <em>Either&#60;E1, Either&#60;E2, A&#62;&#62;</em>. This is something we could not do with <em>Thrower</em>.</p>
<p><strong>Nothing to Declare</strong></p>
<p>Now, we've been returning Exceptions, but what does an <em>Exception </em>give you, really? You get some information about the failure, like an Exception type name, an error message, a stack trace, and possibly a nested Exception. If you know how to recover from an error, are you going to need the stack trace and the error message? No. You don't actually have to return Exceptions to indicate errors if you don't want to. You could just as well return <em>String</em>, <em>Integer</em>, <em>fj.Unit</em>, or your favourite data structure. Or you could return... <em>Nothing</em>.</p>
<p>There's a simpler monad than <em>Either </em>which is often used in functional programming. It's called <em>Option</em> (sometimes known as <a href="http://en.wikibooks.org/wiki/Haskell/Hierarchical_libraries/Maybe" target="_blank"><em>Maybe</em></a>). An example is <a href="http://projects.workingmouse.com/public/functionaljava/artifacts/2.6/javadoc/fj/data/Option.html" target="_blank">Functional Java's fj.data.Option</a> class, which I'll demonstrate briefly here. <em>Option&#60;A&#62;</em> is a lot like a <em>List&#60;A&#62; </em>that can either be empty, or contain a single value of type <em>A</em>. For example:</p>
<pre style="background:#242424;color:#f6f3e8;"><span>
</span>  <span style="color:#cae682;">public</span> <span style="color:#cae682;">static</span> <span style="color:#e5786d;">Option</span>&#60;<span style="color:#e5786d;">Double</span>&#62; divide(<span style="color:#cae682;">double</span> x, <span style="color:#cae682;">double</span> y) <span style="color:#cae682;">{</span>
  <span style="color:#8ac6f2;">  if</span> (y == <span style="color:#e5786d;">0</span>) <span style="color:#cae682;">{</span>
    <span style="color:#8ac6f2;">  return</span> <span style="color:#e5786d;">Option</span>.none();
  <span style="color:#cae682;">  }</span>
  <span style="color:#8ac6f2;">  return</span> <span style="color:#e5786d;">Option</span>.some(x / y);
<span style="color:#cae682;">  }
</span><span>
</span></pre>
<p>This is similar to returning <em>null </em>on failure, except that callers won't be surprised if the method fails to return a value. It's declared in the method signature, after all. <em>Option.none()</em> has the correct type and will respond to methods declared on the <em>Option </em>class. If you want a lazy <em>Option</em>, simply wrap it in a <em>P1</em> like we did with <em>Either</em>.</p>
<p>Not surprisingly, <em>Option </em>comes equipped with monadic methods like fmap (or simply "map") to lift an <em>F&#60;A,B&#62;</em> to an <em>F&#60;Option&#60;A&#62;, Option&#60;B&#62;&#62;</em>, "bind" to chain <em>Option</em>-valued functions together, and "join" to collapse an <em>Option&#60;Option&#60;A&#62;&#62;</em> into an <em>Option&#60;A&#62;</em>. Option's unit function is the static method <em>Option.some</em>. The instance method <em>some() </em>returns the value in the <em>Option</em>, if any. This last one is the <em>Option </em>equivalent to <em>Thrower.extract()</em>.</p>
<p>So, now that we're using <em>Option </em>and <em>Either </em>to indicate recoverable errors, what about unrecoverable errors? Those are the kinds of errors that we're not going to catch, nor expect any reasonable application to catch. They should result in <a href="http://www.martinfowler.com/ieeeSoftware/failFast.pdf" target="_blank">immediate and visible failure</a>. For example, we might decide that it's not reasonable to recover from a critical function if it returns nothing:</p>
<pre style="background:#242424;color:#f6f3e8;"><span>
</span>  <span style="color:#e5786d;">Option</span>&#60;MyAppConfig&#62; config = getAppConfig();
<span style="color:#8ac6f2;">  if</span> (config.isNone()) <span style="color:#cae682;">{</span>
  <span style="color:#8ac6f2;">  throw</span> <span style="color:#8ac6f2;">new</span> <span style="color:#8ac6f2;">Error</span>(<span style="color:#95e454;"><em>"No configuration!"</em></span>);
<span style="color:#cae682;">  }</span> <span style="color:#8ac6f2;">else</span> <span style="color:#cae682;">{</span>
  <span style="color:#99968b;"><em>  // Do stuff with config here.</em></span>
<span style="color:#cae682;">  }</span><span>
</span><span>
</span></pre>
<p>At this point, we have completely obviated Java's checked exceptions mechanism. Recoverable errors are simply returned, and unrecoverable errors are thrown all the way out. We can now construct computations, and even if they might fail we can pass them around, compose them together, extract values from them, etc. All without a <em>throws </em>keyword in sight. The circle is complete.</p>
<p>That's the end of Lazy Error Handling in Java. We've gone everywhere from throwing exceptions lazily, to higher-order chaining and manipulation of exception-throwing computations, to doing away with checked exceptions altogether. I hope you have found this short series educational and as fun to read as it was to write.</p>
<p><strong>END</strong></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Lazy Error Handling in Java, Part 2: Thrower is a Monad]]></title>
<link>http://apocalisp.wordpress.com/?p=14</link>
<pubDate>Fri, 23 May 2008 05:37:44 +0000</pubDate>
<dc:creator>apocalisp</dc:creator>
<guid>http://apocalisp.wordpress.com/?p=14</guid>
<description><![CDATA[In Part 1, we talked about the Thrower interface, and how we could use it to separate error handling]]></description>
<content:encoded><![CDATA[<p>In <a href="http://apocalisp.wordpress.com/2008/05/16/thrower-functor/" target="_blank">Part 1</a>, we talked about the Thrower interface, and how we could use it to separate error handling from the code that produces those errors. We also saw how we could exploit generics to create a <em>functor </em>that can promote an existing function to a function that can handle and throw errors.</p>
<p>In this post, we'll see that the greatest benefit of Thrower is the ability to compose and sequence computations; even computations that may fail, all the while staying type-safe. We'll introduce some new functions which allow us to perform a kind of Thrower arithmetic that in turn will let us manipulate values tucked away in Throwers, without ever having to extract from them, and without any exceptions being thrown or caught.</p>
<p>The ingredients we need are exactly the ingredients needed for a <a href="http://en.wikipedia.org/wiki/Monads_in_functional_programming" target="_blank">monad</a>. That is: <em>A type construction</em>, <em>a unit function, and a </em><em>binding operation.</em> The first ingredient, type construction, we already have. The Thrower interface is generic, so it lets us create a type Thrower&#60;A, E&#62; for any type A, given some Throwable type E.</p>
<p>The unit function is simple enough. It just creates a new Thrower that completely preserves the value that we put in it:</p>
<pre style="color:#f6f3e8;background:#242424;">  <span style="color:#cae682;">
  public</span> <span style="color:#cae682;">static</span> &#60;A, E <span style="color:#cae682;">extends</span> <span style="color:#8ac6f2;">Throwable</span>&#62; Thrower&#60;A, E&#62; unit(<span style="color:#cae682;">final</span> A a) <span style="color:#cae682;">{</span>
    <span style="color:#8ac6f2;">return</span> <span style="color:#8ac6f2;">new</span> Thrower&#60;A, E&#62;() <span style="color:#cae682;">{</span>
<span style="color:#cae682;">      </span><span style="color:#cae682;">public</span><span style="color:#cae682;"> A extract()</span> <span style="color:#cae682;">{</span>
        <span style="color:#8ac6f2;">return</span> a;
      <span style="color:#cae682;">}</span>
    <span style="color:#cae682;">}</span>;
  <span style="color:#cae682;">}

</span></pre>
<p>The final ingredient for our Thrower monad is the <em>bind</em> function. It takes a Thrower and feeds its result to a function that returns another Thrower:</p>
<pre style="color:#f6f3e8;background:#242424;">  <span style="color:#cae682;">
  public</span> <span style="color:#cae682;">static</span> &#60;A, B, E <span style="color:#cae682;">extends</span> <span style="color:#8ac6f2;">Throwable</span>&#62; Thrower&#60;B, E&#62;
  bind(<span style="color:#cae682;">final</span> Thrower&#60;A, E&#62; a, <span style="color:#cae682;">final</span> F&#60;A, Thrower&#60;B, E&#62;&#62; f) <span style="color:#cae682;">{</span>
    <span style="color:#8ac6f2;">return</span> <span style="color:#8ac6f2;">new</span> Thrower&#60;B, E&#62;() <span style="color:#cae682;">{</span>
<span style="color:#cae682;">      </span><span style="color:#cae682;">public</span><span style="color:#cae682;"> B extract()</span> <span style="color:#cae682;">throws</span> E <span style="color:#cae682;">{</span>
        <span style="color:#8ac6f2;">return</span> f.f(a.extract()).extract();
      <span style="color:#cae682;">}</span>
    <span style="color:#cae682;">}</span>;
  <span style="color:#cae682;">}

</span></pre>
<p>Check what this actually does. It creates a new Thrower, whose extract() method calls the extract() method on the first Thrower and applies the function f to the result. Nothing actually happens when we call <em>bind</em>, except that a new future call to the provided function is created. So we're applying <em>f</em> to the contents of the Thrower <em>a,</em> but not suffering any consequences until later, whenever we decide to call extract() on the result of <em>bind</em>.</p>
<p>Note that we can only compose, in this manner, Throwers that throw the same Throwable type. To combine Throwers of different kinds of exceptions, you would need to return a <em>Thrower&#60;Thrower&#60;A,E1&#62;,E2&#62;&#62;</em>, or something like a <em>Thrower2&#60;B,E1,E2&#62;</em> which can throw either E1 or E2. You cannot create a new generic Throwable like <em>MyException&#60;E1, E2&#62;</em> as the disjoint union of two Throwables, since subclasses of Throwable are not allowed to be generic due to Java's runtime type erasure. Normally, I don't care about the types of exceptions to that level of detail anyway, so if I need to work with different species of them, I just use the <em>Exception</em> type. That's exactly what we'll do in the example further down.</p>
<p>Now, notice the second argument to <em>bind:</em></p>
<pre style="color:#f6f3e8;background:#242424;">          <span style="color:#cae682;">
  final</span> F&#60;A, Thrower&#60;B, E&#62;&#62; f</pre>
<p>This is a pretty useful kind of thing. It's a function that takes an <em>A</em> and either returns a <em>B</em> or throws an <em>E</em>. So it's kind of like a Thrower that takes an argument. It's actually a <a href="http://sigfpe.blogspot.com/2006/06/monads-kleisli-arrows-comonads-and.html?showComment=1162433100000" target="_blank">Kleisli Arrow</a> for the Thrower monad. This is something we'll need often, so let's make them easy for ourselves to create:</p>
<pre style="color:#f6f3e8;background:#242424;">  <span style="color:#cae682;">
  public</span> <span style="color:#cae682;">abstract</span> <span style="color:#cae682;">class</span> Partial&#60;A, B, E <span style="color:#cae682;">extends</span> <span style="color:#8ac6f2;">Throwable</span>&#62; <span style="color:#cae682;">implements</span> F&#60;A, Thrower&#60;B, E&#62;&#62; <span style="color:#cae682;">{</span>
<span style="color:#cae682;">
  protected</span><span style="color:#cae682;"> </span><span style="color:#cae682;">abstract</span><span style="color:#cae682;"> B run(</span><span style="color:#cae682;">final</span><span style="color:#cae682;"> A a)</span> <span style="color:#cae682;">throws</span> E;

<span style="color:#cae682;">    </span><span style="color:#cae682;">public</span><span style="color:#cae682;"> </span><span style="color:#cae682;">final</span><span style="color:#cae682;"> Thrower&#60;B, E&#62; f(</span><span style="color:#cae682;">final</span><span style="color:#cae682;"> A a)</span> <span style="color:#cae682;">{</span>
      <span style="color:#cae682;">final</span> Partial&#60;A, B, E&#62; self = <span style="color:#cae682;">this</span>;
      <span style="color:#8ac6f2;">return</span> <span style="color:#8ac6f2;">new</span> Thrower&#60;B, E&#62;() <span style="color:#cae682;">{</span>
<span style="color:#cae682;">        </span><span style="color:#cae682;">public</span><span style="color:#cae682;"> B extract()</span> <span style="color:#cae682;">throws</span> E <span style="color:#cae682;">{</span>
          <span style="color:#8ac6f2;">return</span> self.run(a);
        <span style="color:#cae682;">}</span>
      <span style="color:#cae682;">}</span>;
    <span style="color:#cae682;">}</span>
  <span style="color:#cae682;">}
   </span></pre>
<p>It's called Partial because it models a partial function, a function whose result is undefined for some values (i.e. it might throw an exception instead of returning a value). We've abstracted away all the Thrower stuff (it's always going to work the same anyway), so concrete subclasses will only have to override the <em>run</em> method and do what a partial function would: turn an <em>A </em>into a <em>B</em> or throw an <em>E.</em></p>
<p>It might seem that this has taken us full circle, that this was all an exercise in futility if we're back to just writing methods that throw exceptions. But no, what we have so far actually gives us a lot of power under the hood.</p>
<p>For the token contrived example, let's say that you have an abstract class which models an action to get some object from the network given a URLConnection, possibly throwing a network error:</p>
<pre style="background:#242424;color:#f6f3e8;">    <span style="color:#cae682;">
  public</span> <span style="color:#cae682;">abstract</span> <span style="color:#cae682;">class</span> NetTalker&#60;A&#62; <span style="color:#cae682;">extends</span> Partial&#60;<span style="color:#e5786d;">URLConnection</span>, A, <span style="color:#8ac6f2;">Exception</span>&#62;<span style="color:#cae682;"> {</span><span style="color:#cae682;">}

</span></pre>
<p>Even though this class has no body, its intent is very clear. Users of our API will just have to to override <em>run</em> to do something useful with a connection. But NetTalkers just use connections; the construction of URLConnections will be implementation-specific. We'll use another class:</p>
<pre style="background:#242424;color:#f6f3e8;">  <span style="color:#cae682;">
  public abstract class</span> URLConnector <span style="color:#cae682;">extends Partial</span>&#60;<span><span style="color:#e5786d;">URL</span></span>, <span><span><span style="color:#e5786d;">URLConnection</span></span></span>, <span style="color:#8ac6f2;">Exception</span>&#62; <span style="color:#cae682;">{}

</span></pre>
<p>Where concrete subclasses create different concrete URLConnections. To get an A from a URL, given some URLConnector c (that knows how to make HttpURLConnections) and some NetTalker n, we can do the following:</p>
<pre style="color:#f6f3e8;background:#242424;">          <span style="color:#cae682;">
  </span>Thrower&#60;A, <span style="color:#8ac6f2;">Exception</span>&#62;<span style="color:#cae682;"> </span>t = bind(c.f(<span style="color:#cae682;"><span style="color:#95e454;"><em>"http://foo.bar"</em></span></span>),<span style="color:#cae682;"> </span>n)<span style="color:#cae682;">;

</span></pre>
<p>Again, this doesn't give you the object of type <em>A</em>, it merely gives you a Thrower which either returns the A or throws an exception. It's lazy. You can take <em>t</em> and bind it to a <em>Partial</em> that takes an <em>A</em> and, say, writes it to a file, again returning a lazy Thrower. Then, when something calls <em>extract()</em> on it, the whole enchilada of operations will be executed in one go.</p>
<p>Or, if you have a whole list of Throwers, you could turn them into a Thrower that returns a list:</p>
<pre style="color:#f6f3e8;background:#242424;">  <span style="color:#cae682;">

  public</span> <span style="color:#cae682;">static</span> &#60;A, E <span style="color:#cae682;">extends</span> <span style="color:#8ac6f2;">Throwable</span>&#62; Thrower&#60;<span style="color:#e5786d;">List</span>&#60;A&#62;, E&#62; sequence(<span style="color:#cae682;">final</span> <span style="color:#e5786d;">List</span>&#60;Thrower&#60;A, E&#62;&#62; ts)
  <span style="color:#cae682;">{</span>
    <span style="color:#8ac6f2;">return</span> ts.foldRight(Throwers.&#60;<span style="color:#e5786d;">List</span>&#60;A&#62;, E&#62; unit(<span style="color:#e5786d;">List</span>.&#60;A&#62;nil()),
      Throwers.&#60;A, <span style="color:#e5786d;">List</span>&#60;A&#62;, <span style="color:#e5786d;">List</span>&#60;A&#62;, E&#62; liftM2(List.&#60;A&#62; cons()));
  <span style="color:#cae682;">}

</span></pre>
<p>The above collapses an entire list of throwers into a single thrower that returns all their results in one list. Here, List is a fj.data.List from <a href="http://functionaljava.org" target="_blank">Functional Java</a>, not java.util.List, although this can be made to work quite easily with the Java Collections Framework by defining nil(), cons(), and <a href="http://apocalisp.wordpress.com/2008/05/08/12/" target="_blank">foldRight</a>(). liftM2 is almost exactly like fmap from Part 1, except that it lifts <a href="http://tinyurl.com/589srb" target="_blank">functions of arity-2</a>.</p>
<p>We've only had a slight taste of what we can do with monads, even in Java, and there are relationships between <em>fmap</em>, <em>bind</em>, and <em>unit</em> that are worth understanding in detail. As you can see, it's a powerful abstraction that can be applied to a wide variety of problems. It doesn't stop with Throwers. Notice that NetTalker is also a generic type, with a single type parameter. Yes, it too is a functor. It too can be a monad, and can be composed as we did with Throwers. In fact, here's fmap for NetTalker:</p>
<pre style="background:#242424 none repeat scroll 0 50%;color:#f6f3e8;"> <span style="color:#cae682;">
  public</span> <span style="color:#cae682;">static</span> &#60;A,B&#62; <span style="color:#e5786d;">F</span>&#60;NetTalker&#60;A&#62;, NetTalker&#60;B&#62;&#62;
    fmap(<span style="color:#cae682;">final</span> <span style="color:#e5786d;">F</span>&#60;A,B&#62; f) <span style="color:#cae682;">{</span>
      <span style="color:#8ac6f2;">return</span> <span style="color:#8ac6f2;">new</span> <span style="color:#e5786d;">F</span>&#60;NetTalker&#60;A&#62;, NetTalker&#60;B&#62;&#62;()<span style="color:#cae682;"> {</span>
<span style="color:#cae682;">        </span><span style="color:#cae682;">public</span><span style="color:#cae682;"> NetTalker&#60;B&#62; f(</span><span style="color:#cae682;">final</span><span style="color:#cae682;"> NetTalker&#60;A&#62; a)</span><span style="color:#cae682;"> {</span>
          <span style="color:#8ac6f2;">return</span> <span style="color:#8ac6f2;">new</span> NetTalker&#60;B&#62;()<span style="color:#cae682;"> {</span>
<span style="color:#cae682;">            </span><span style="color:#cae682;">public</span><span style="color:#cae682;"> B run(</span><span style="color:#e5786d;">URLConnection</span><span style="color:#cae682;"> </span><span style="color:#cae682;">u</span><span style="color:#cae682;">)</span> <span style="color:#cae682;">throws</span> <span style="color:#8ac6f2;">Exception</span><span style="color:#cae682;"> {</span>
              <span style="color:#8ac6f2;">return</span> f.f(a.f(u));
            <span style="color:#cae682;">}</span>
        <span style="color:#cae682;">  }</span>;
        <span style="color:#cae682;">}</span>
      <span style="color:#cae682;">}</span>;
    <span style="color:#cae682;">}

</span></pre>
<p>I wonder what other types are monadic.</p>
<p>Unfortunately, you'll find that you can't write a generic Monad class in Java. Poor Java's type system is not sophisticated enough to understand <a href="http://lambda-the-ultimate.org/node/2579" target="_blank">higher-kinded types</a>, nor would that be sane without type inference in the compiler, which Java also lacks. You will have to write bind and unit for every kind of monad that you need, as well as all operations based on them (fmap, sequence, etc.), or dispense with the type system (in which case you may as well be writing Ruby), or switch to <a href="http://scala-lang.org" target="_blank">Scala</a>.</p>
<p>I hope you enjoyed this little journey through monads and exceptions in Java. In <a href="http://apocalisp.wordpress.com/2008/06/04/throwing-away-throws/" target="_self">Part 3</a> of this series, we will look at how we can remove <em>try</em>, <em>catch</em>, and <em>throw</em>s entirely from our code, in favor of <em>unit</em>, <em>bind</em>, <em>fmap</em>, and <em>join</em>.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Advanced C# 3.0 : Part 2 - Everyday Tasks with New Solutions]]></title>
<link>http://dcarr.wordpress.com/2008/05/22/advanced-c-30-part-2-everyday-tasks-with-new-solutions/</link>
<pubDate>Thu, 22 May 2008 19:31:10 +0000</pubDate>
<dc:creator>Damon Wilder Carr</dc:creator>
<guid>http://dcarr.wordpress.com/2008/05/22/advanced-c-30-part-2-everyday-tasks-with-new-solutions/</guid>
<description><![CDATA[Part 2 : Digging Deeper into Lambadas, Extension Methods, and Linq
The world’s most common extensi]]></description>
<content:encoded><![CDATA[<h3>Part 2 : Digging Deeper into Lambadas, Extension Methods, and Linq</h3>
<p>The world’s most common extension method and an attempt at a definitive version.</p>
<p>In this post I'll be digging deeper into doing things I've always wanted to have in .NET yet didn't. For example, I know I am not alone in wanting an IList (be it an IList&#60;T&#62; or a simple non-generic IList) to provide me a .foreach method as you get in a List&#60;T&#62;). This is just one of many things we address here (and more).</p>
<h1>From the concrete to the abstract</h1>
<p>I was having problems with entries in my path environmental variable, and I wanted an easy way to flag bad entries and also allow me to move the entries in the list up or down easily. This was made apparent by my use of a tool called 'Dependency Walker'. It's hard to live without but that's another post. See the screen shot below:</p>
<p><a href="http://dcarr.files.wordpress.com/2008/05/image-0001.png"><img style="border-width:0;" alt="Image-0001" src="http://dcarr.files.wordpress.com/2008/05/image-0001-thumb.png" width="458" height="316" /></a></p>
<p><a href="http://www.dependencywalker.com/">Click here to go to 'Dependency Walker'</a></p>
<h1>Test to Code</h1>
<p><a href="http://11011.net/software/vspaste"></a></p