<?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://en.wordpress.com/tag/functional-programming/</link>
	<description>Feed of posts on WordPress.com tagged "functional-programming"</description>
	<pubDate>Fri, 25 Dec 2009 20:21:49 +0000</pubDate>

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

<item>
<title><![CDATA[Sequential script loading on demand]]></title>
<link>http://aabs.wordpress.com/2009/12/16/sequential-script-loading-on-demand/</link>
<pubDate>Wed, 16 Dec 2009 00:26:13 +0000</pubDate>
<dc:creator>aabs</dc:creator>
<guid>http://aabs.wordpress.com/2009/12/16/sequential-script-loading-on-demand/</guid>
<description><![CDATA[This little script uses the JQuery getScript command, enforcing sequential loading order to ensure s]]></description>
<content:encoded><![CDATA[This little script uses the JQuery getScript command, enforcing sequential loading order to ensure s]]></content:encoded>
</item>
<item>
<title><![CDATA[Python Functional Programming for Mathematicians]]></title>
<link>http://mvngu.wordpress.com/2009/12/12/python-functional-programming-for-mathematicians/</link>
<pubDate>Sat, 12 Dec 2009 23:20:04 +0000</pubDate>
<dc:creator>mvngu</dc:creator>
<guid>http://mvngu.wordpress.com/2009/12/12/python-functional-programming-for-mathematicians/</guid>
<description><![CDATA[This tutorial discusses some techniques of functional programming that might be of interest to mathe]]></description>
<content:encoded><![CDATA[This tutorial discusses some techniques of functional programming that might be of interest to mathe]]></content:encoded>
</item>
<item>
<title><![CDATA[MDU Syllabus - 8th Semester]]></title>
<link>http://ashishmalikit.wordpress.com/2009/12/03/mdu-syllabus-8th-semester/</link>
<pubDate>Thu, 03 Dec 2009 19:42:32 +0000</pubDate>
<dc:creator>ashishmalik10</dc:creator>
<guid>http://ashishmalikit.wordpress.com/2009/12/03/mdu-syllabus-8th-semester/</guid>
<description><![CDATA[Maharshi Dayanand University Discipline : Bachelor of Engineering / Bachelor Of Technology Branch : ]]></description>
<content:encoded><![CDATA[Maharshi Dayanand University Discipline : Bachelor of Engineering / Bachelor Of Technology Branch : ]]></content:encoded>
</item>
<item>
<title><![CDATA[F# by Microsoft Research]]></title>
<link>http://robertoerazo.wordpress.com/2009/11/30/f-by-microsoft-research/</link>
<pubDate>Mon, 30 Nov 2009 12:15:32 +0000</pubDate>
<dc:creator>robertoerazo</dc:creator>
<guid>http://robertoerazo.wordpress.com/2009/11/30/f-by-microsoft-research/</guid>
<description><![CDATA[Dentro de los lenguajes de programacion que Microsoft ha vinculado al Framework de .NET aparte de lo]]></description>
<content:encoded><![CDATA[Dentro de los lenguajes de programacion que Microsoft ha vinculado al Framework de .NET aparte de lo]]></content:encoded>
</item>
<item>
<title><![CDATA[We call it OPA]]></title>
<link>http://dutherenverseauborddelatable.wordpress.com/2009/11/28/we-call-it-opa/</link>
<pubDate>Sat, 28 Nov 2009 19:15:55 +0000</pubDate>
<dc:creator>yoric</dc:creator>
<guid>http://dutherenverseauborddelatable.wordpress.com/2009/11/28/we-call-it-opa/</guid>
<description><![CDATA[Web applications are nice. They&#8217;re useful, they&#8217;re cross-platform, users need no install]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p style="text-align:justify;">Web applications are nice. They&#8217;re useful, they&#8217;re cross-platform, users need no installation, no upgrades, no maintenance, not even the computing or storage power to which they are used. As weird as it may sound, I&#8217;ve even seen announcements for web applications supposed to run your games on distant high-end computers so that you can actually play on low-end computers. Go web application!</p>
<p style="text-align:justify;">Of course, there are a few downsides to web applications. Firstly, they require a web connexion. Secondly, they are largely composed of <em>plumbing</em>. Finally, ensuring their security is a constant fight.</p>
<p><!--more--></p>
<h3>How many pipes do you need?</h3>
<p style="text-align:justify;">If you have ever developed a web application, you know what I mean by plumbing: just writing an online TODO list &#8212; the equivalent of maybe twenty minutes of work in Visual Basic, in Python, Java or Objective-C &#8212; requires mixing an insane amount of languages, to define your user interface (HTML, JavaScript, CSS), to define your storage (DDL, DML, DCL, plus possibly an ORM language), to get your server and your client to communicate (XML, more JavaScript, PHP or one of its competitors, as well as some HTTP and a little MIME configuration), to launch your application (whichever configuration languages are used by your server). Of course, if your application is a bit more complex and requires something like compatibility with smartphones, or like distant storage, or distributed computing, or backups, or modularity (in the world of the web, it&#8217;s called &#8220;web services&#8221;)&#8230; well, you will probably require a few additional languages.</p>
<p style="text-align:justify;">All of this is just <em>plumbing</em>. Only once you have written it can you concentrate on the core of the application. And once the application is written, the pain is just starting, because chances are that your application can be attacked by hijacking the link between your user interface and the core (cross-site scripting) or between the core and the storage (SQL injection) or by keeping the user interface and replacing the application core (man-in-the-middle attacks) or by replacing the user interface by a malicious client or by taking the place of a currently connected user to steal some of its credentials (rebinding) or by taking advantage of low-level bugs (buffer over/underflows), etc.</p>
<p style="text-align:justify;">None of this is a show-stopper, of course &#8212; just take a look at the web and you will see thousands of web applications. Just like the complexity of Software Development Kits in the early days of Windows, MacOS or X didn&#8217;t stop adventurous hackers from developing desktop applications. But of course, if twenty-five years of desktop application development have taught us one thing, it is that the life of developers can be made easier. Nowadays, a few generations of SDKs later, Windows developers have .Net, C# and Visual Studio, Macintosh developers have Cocoa, Objective-C and XCode, while X-based developers have the libraries of Gnome/KDE, Python and a variety of programming environments. The growing popularity (and libraries) of Haskell, F#, OCaml, Scala and other functional programming languages could mean that one of the next generations of SDKs will increase safety and security.</p>
<p style="text-align:justify;">The web hasn&#8217;t quite reached that stage yet. Even the state-of-the-art in web frameworks only provides features slightly more advanced than early Windows/Mac/X SDKs: low-level bindings for low-level mechanisms, designed to ensure low-level properties. Or, rephrased differently, in the current state of web development, GMail, Google Maps or Facebook are still considered complicated applications, although they are conceptually quite simple and should therefore be equally simple to implement.</p>
<p style="text-align:justify;">We can do better. How? By removing the need for plumbing. By providing automated mechanisms for ensuring high-level security properties. By providing language support for common patterns.</p>
<h3>Enter OPA</h3>
<p style="text-align:justify;">Let me introduce OPA. OPA, or One Pot Application, is a complete development platform for web applications and web services. Development in OPA requires no plumbing. Applications developed with OPA are automatically checked for safety and security before they are executed. Applications developed with OPA are automatically (and provably) immune to cross-site scripting, to SQL injections and to most existing forms of attacks. And OPA provides language support for storage, communication between client and server (Ajax and Comet), concurrency, distribution, mobility, etc.</p>
<p style="text-align:justify;">With OPA, we intend to skip several generations of SDKs and provide right now a high-level and modern programming platform. OPA has been 6 years in the making: 4 years of sketches, mockups and prototypes as part of academic research projects and 2 years of actual implementation at <a href="http://www.mlstate.com">MLstate</a>. A few days ago, OPA has officially entered <em>demonstrable</em> status. Not quite ready for prime time, but definitely usable for development. Do you want to write an online note-taking application? That&#8217;s about 20 lines of code, from scratch. A minimal chat? About 30 lines. A multi-channel, distributed chat? About 80 lines. A minesweeper? About 100. We&#8217;re using it to develop utilities, content management systems, tools for administrations and games.</p>
<p style="text-align:justify;">Pre-alpha builds of OPA have been distributed to selected partners. A public version will be made available within a few weeks, as well as commercial applications developed with OPA. In the meantime, we are busy improving the syntax, completing the standard library, making error messages intelligible, fixing the bugs and extending the range of safety and security checks.</p>
<p style="text-align:justify;">Interested? Well, few details are public at this time. However, you can take a look at <a href="http://vidiowiki.com/watch/t53c29y/">a video</a> recorded during ICFP presenting OPA and MLstate.</p>
<p style="text-align:justify;">Stay tuned.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Clojure: Return values]]></title>
<link>http://dahliabock.wordpress.com/2009/11/22/clojure-return-values/</link>
<pubDate>Sun, 22 Nov 2009 14:10:28 +0000</pubDate>
<dc:creator>Dahlia Bock</dc:creator>
<guid>http://dahliabock.wordpress.com/2009/11/22/clojure-return-values/</guid>
<description><![CDATA[Like in Ruby, there is no explicit call in a function to return values, the last expression of a fun]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Like in Ruby, there is no explicit call in a function to return values, the last expression of a function is evaluated and used as its return value.</p>
<p>Consider the following 2 functions:</p>
<pre class="textmate-source blackboard"><span class="text text_plain"><span class="meta meta_paragraph meta_paragraph_text">(defn hello-with-println [name]
</span>    <span class="meta meta_paragraph meta_paragraph_text">(println "Hello," name))
</span>    

<span class="meta meta_paragraph meta_paragraph_text">(defn hello-with-str [name]
</span>    <span class="meta meta_paragraph meta_paragraph_text">(str "Hello, " name))</span></span></pre>
<p>The first function when evaluated on the REPL (read-eval-print-loop), which is an interactive programming environment, returns the following:</p>
<pre class="textmate-source blackboard"><span class="text text_plain">
user=&#62; (hello-with-println "punk")
Hello, punk
nil</span></pre>
<p>The second function returns:</p>
<pre class="textmate-source blackboard"><span class="text text_plain">
user=&#62; (hello-with-str "munk")
"Hello, munk"
</span></pre>
<p>At first glance, these two functions seem to be doing almost the same thing &#8211; takes in a string input, which is a name, and outputs a string that says Hello to that name. However, <code>hello-with-println</code> returns <code>nil</code> while <code>hello-with-str</code> returns the evaluation of the <code>str</code> function.</p>
<p>This can be proven further with special variables in the REPL. When working within the REPL, the results of evaluating the three most recent expressions are stored in the special variables <code>*1</code>, <code>*2</code> and <code>*3</code>. If I call <code>hello-with-println</code> twice with the inputs &#8220;munk&#8221; and &#8220;punk&#8221; and use the special variables *1 and *2 to get the results of those expressions, I get the following:</p>
<pre class="textmate-source blackboard"><span class="text text_plain">
user=&#62; (str *1 " and " *2)
" and "
</span></pre>
<p>If I do the same with <code>hello-with-str</code>, I get the following output:</p>
<pre class="textmate-source blackboard"><span class="text text_plain">
user=&#62; (str *1 " and " *2)
"Hello, punk and Hello, munk"
</span></pre>
<p>When <code>hello-with-println</code> was used, there were no return values so the special variables were empty unlike in <code>hello-with-str</code>.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Loving Clojure]]></title>
<link>http://devender.wordpress.com/2009/11/18/loving-clojure/</link>
<pubDate>Thu, 19 Nov 2009 02:02:15 +0000</pubDate>
<dc:creator>devender</dc:creator>
<guid>http://devender.wordpress.com/2009/11/18/loving-clojure/</guid>
<description><![CDATA[I seem to be liking Clojure &#8230; Let me backup a bit, in the last couple of weeks I have been deb]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I seem to be liking Clojure &#8230;</p>
<p>Let me backup a bit, in the last couple of weeks I have been debating between picking up Scala or Clojure (don&#8217;t get me wrong Ruby is still my favorite).</p>
<p>I always wanted to pick up a functional programming language so I dabbled a bit with Erlang and Haskell, liked Haskell a lot but without much practice it kind of died (sad times)  and Scala seems too much like Java, yeah I know it seems to have a bigger crowd than Clojure and there are a lot of big names behind it.</p>
<p>Maybe that&#8217;s exactly why I choose Clojure (since its the underdog), or cause it is different enough from Java or simply cause it has a better syntax and seems more elegant (apparently Clojure has better integration with Java, don&#8217;t quote me on it), anyways I decided to learn Clojure.</p>
<p>Peepcode has a nice <a href="http://peepcode.com/products/functional-programming-with-clojure">screen-cast</a> to get you started off on Clojure. If you are on the Mac there is a nice <a href="http://github.com/nullstyle/clojure-tmbundle">bundle</a> for TextMate and anywhere else Netbeans with the <a href="http://enclojure.org/">enclojure</a> plugin seems to be the best.</p>
<p>On a side note it seems more and more that Netbeans has the latest and greatest plugins for everything, then comes IntelliJ and finally eclipse, what&#8217;s going on with eclipse ? has it reached its peak and now it will start dropping off ? but on the flip side there seems to be more and more apps built on top of the Eclipse RCP like Xmind, so is Eclipse no longer going to be the leader of the IDE and just become a platform for building RCPs. This of course depends  on what Oracle is going to do with NetBeans, I really hope they give the same amount of love to NetBeans as Sun did.</p>
<p>Ok getting back to Clojure, don&#8217;t get your panties in a bunch when you see all those parenthesis, it is just the layout that is shocking, indent it well and it is no more than what you are used to.</p>
<p>Here&#8217;s an example<br />
(defn fac<br />
&#34;Returns the factorial of n, which must be a positive integer.&#34;<br />
[n]<br />
(if (= n 1)<br />
1<br />
(* n (fac (- n 1)))<br />
)<br />
Is same as<br />
(defn fac [n] (if (= n 1) 1 (* n (fac (- n 1)))))<br />
But the first one is a lot more easier on the eyes (even brain?) than the second one. Most examples that you see look like the second one and it frightens people, don&#8217;t let that stop you take my word and go for it.</p>
<p>Clojure seems to be very easy to pick up, things seem very intuitive, like the other day I was wondering, how to return a default value from a map if the key is not found and there is was right there in the api.<br />
(map key default-value)<br />
So simple! I was easily able to extend the examples that came with the peepcode screencast. Anyways I have started on this path, let&#8217;s see where it goes.</p>
<p>Update 2009/12/03</p>
<p>- Looked at the Clojure source code, looks squeaky clean, I applied to become a member so that I can expand on the test coverage, hopefully they will accept me.</p>
<p>-It is <em>(load-file &#8220;hello.clj&#8221;)</em> and not <em>load-file &#8220;hello.clj&#8221;</em> , I keep forgetting that and after a few mins I realize it.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Clojure: Getting back to the basics - Lexical Scoping]]></title>
<link>http://dahliabock.wordpress.com/2009/11/18/clojure-getting-back-to-the-basics-lexical-scoping/</link>
<pubDate>Wed, 18 Nov 2009 21:50:10 +0000</pubDate>
<dc:creator>Dahlia Bock</dc:creator>
<guid>http://dahliabock.wordpress.com/2009/11/18/clojure-getting-back-to-the-basics-lexical-scoping/</guid>
<description><![CDATA[Functional programming has always been a nightmare for me and it started off in college with a class]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Functional programming has always been a nightmare for me and it started off in college with a class called <a href="http://www.cs.cmu.edu/~me/212/schedule.html" target="_blank"><em>15-212: Principles of Programming</em></a>, which was taught in <a href="http://www.amazon.com/Introduction-Programming-International-Computer-Science/dp/0201398206" target="_blank">SML</a>. Almost everything that was taught in that class went over my head and it&#8217;s a miracle that I managed to get a <em>B</em> for it. When I graduated, I swore I never wanted to have anything to do with functional programming ever again, until a few of my coworkers started talking about languages like <a href="http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/" target="_blank">F#</a>, <a href="http://www.scala-lang.org/" target="_blank">Scala</a> and <a href="http://clojure.org" target="_blank">Clojure</a> last year. I have tried to avoid it for as long as I can, but it has proven inevitable.</p>
<p>In starting to read and play with Clojure, I have had to learn a lot of basic concepts that I might or might not have known before. I will attempt to highlight those concepts as I stumble upon them and illustrate them with code snippets that I find or ones that I wrote myself. Pardon the juvenile approach, I find I remember things better if I write them down or explain it to someone.</p>
<p><strong><em>Lexical Scoping</em></strong> &#8211; with lexical or static scope, a variable always refers to its top-level environment. You can always determine a value of a variable based on just reading the code, substituting variable bindings as you go. Of course most programming languages work this way, I just never knew there was a term for it.</p>
<p>Here&#8217;s some code (<a href="http://java.ociweb.com/mark/clojure/article.html" target="_blank">taken from this Clojure tutorial by R. Mark Volkmann</a>) that illustrates lexical scoping and the usages of <code>def</code>, <code>let</code> and <code>binding</code>.</p>
<pre class="textmate-source blackboard"><span class="text text_plain"><span class="meta meta_paragraph meta_paragraph_text">(def v 1) ; v is a global binding
</span>
<span class="meta meta_paragraph meta_paragraph_text">(defn f1 []
</span>  <span class="meta meta_paragraph meta_paragraph_text">(println "f1: v =" v))
</span>
<span class="meta meta_paragraph meta_paragraph_text">(defn f2 []
</span>  <span class="meta meta_paragraph meta_paragraph_text">(println "f2: before let v =" v)
  (let [v 2]
</span>    <span class="meta meta_paragraph meta_paragraph_text">(println "f2: in let, v =" v)
    (f1))
</span>  <span class="meta meta_paragraph meta_paragraph_text">(println "f2: after let v =" v))
</span>
<span class="meta meta_paragraph meta_paragraph_text">(defn f3 []
</span>  <span class="meta meta_paragraph meta_paragraph_text">(println "f3: before binding v =" v)
  (binding [v 3]
</span>    <span class="meta meta_paragraph meta_paragraph_text">(println "f3: in binding, v =" v)
    (f1))
</span>  <span class="meta meta_paragraph meta_paragraph_text">(println "f3: after binding v =" v))
</span>
<span class="meta meta_paragraph meta_paragraph_text">(defn f4 []
</span> <span class="meta meta_paragraph meta_paragraph_text">(def v 4))
</span></span></pre>
<p>Calling <code>f2</code> spits out the following output:</p>
<pre class="textmate-source blackboard"><span class="text text_plain">
<span class="meta meta_paragraph meta_paragraph_text">f2: before let v = 1</span>
<span class="meta meta_paragraph meta_paragraph_text">f2: in let, v = 2</span>
<span class="meta meta_paragraph meta_paragraph_text">f1: v = 1</span>
<span class="meta meta_paragraph meta_paragraph_text">f2: after let v = 1</span></span></pre>
<p>The value of <code>v</code> is 2 only within the <code>let</code> form, and functions that are called within the body cannot see the local bindings of <code>let</code>.</p>
<p>Calling <code>f3</code>:</p>
<pre class="textmate-source blackboard"><span class="text text_plain">
<span class="meta meta_paragraph meta_paragraph_text">f3: before binding v = 1</span>
<span class="meta meta_paragraph meta_paragraph_text">f3: in binding, v = 3</span>
<span class="meta meta_paragraph meta_paragraph_text">f1: v = 3</span>
<span class="meta meta_paragraph meta_paragraph_text">f3: after binding v = 1</span></span></pre>
<p>The <code>binding</code> macro is similar to <code>let</code>, but it creates thread-local values temporarily for existing global bindings. These new values are seen within the form and the functions that are called from within that form.</p>
<p>Calling <code>f4: (println "after calling f4, v =" v)</code>:<br />
<code>after calling f4, v = 4</code></p>
<p>This actually changes the value of the global binding. Now calling <code>f2</code> and <code>f3</code> will have the following output:</p>
<pre class="textmate-source blackboard"><span class="text text_plain">
<span class="meta meta_paragraph meta_paragraph_text">f2: before let v = 4</span>
<span class="meta meta_paragraph meta_paragraph_text">f2: in let, v = 2</span>
<span class="meta meta_paragraph meta_paragraph_text">f1: v = 4</span>
<span class="meta meta_paragraph meta_paragraph_text">f2: after let v = 4</span>
<span class="meta meta_paragraph meta_paragraph_text">nil</span>
<span class="meta meta_paragraph meta_paragraph_text">f3: before binding v = 4</span>
<span class="meta meta_paragraph meta_paragraph_text">f3: in binding, v = 3</span>
<span class="meta meta_paragraph meta_paragraph_text">f1: v = 3</span>
<span class="meta meta_paragraph meta_paragraph_text">f3: after binding v = 4</span>
<span class="meta meta_paragraph meta_paragraph_text">nil</span></span></pre>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Reactive Extensions Now Available - This is Exciting Work]]></title>
<link>http://team.pushbomb.com/2009/11/18/reactive-extensions-now-available-this-is-exciting-work/</link>
<pubDate>Wed, 18 Nov 2009 13:20:07 +0000</pubDate>
<dc:creator>Damon Wilder Carr</dc:creator>
<guid>http://team.pushbomb.com/2009/11/18/reactive-extensions-now-available-this-is-exciting-work/</guid>
<description><![CDATA[vLabs: Reactive Extensions for .NET (Rx) &nbsp; http://msdn.microsoft.com/en-us/devlabs/ee794896.asp]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><h3>vLabs: Reactive Extensions for .NET (Rx)</h3>
<p>&#160;</p>
<p><a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx">http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx</a></p>
<p>&#160;</p>
<div>
<div>
<div><img src="http://i.msdn.microsoft.com/ee794896.DevLabs_Rx_Project%28en-us%29.png" alt="" align="Left" /></div>
</div>
<p>&#160;</p>
</div>
<h4>About Rx</h4>
<p>Rx is a library for composing asynchronous and event-based programs using observable collections.</p>
<p>The “A” in “AJAX” stand for asynchronous, and indeed modern Web-based and Cloud-based applications are fundamentally asynchronous. In fact, Silverlight bans all blocking networking and threading operations. Asynchronous programming in by no means restricted to Web and Cloud scenarios, however. Traditional desktop applications also have to maintain responsiveness in the face of long latency IO operations and other expensive background tasks.</p>
<p>Another common attribute of interactive applications, whether Web/Cloud or client-based, is that they are event-driven. The user interacts with the application via a GUI that receives event streams asynchronously from the mouse, keyboard, and other inputs.</p>
<p>Rx is a superset of the standard LINQ sequence operators that exposes asynchronous and event-based computations as push-based, observable  collections via the new .NET 4.0 interfaces IObservable&#60;T&#62; and IObserver&#60;T&#62;.  These are the mathematical dual of the familiar IEnumerable&#60;T&#62; and IEnumerator&#60;T&#62; interfaces for pull-based, enumerable collections in the .NET framework.</p>
<p>The IEnumerable&#60;T&#62; and IEnumerator&#60;T&#62; interfaces allow developers to create reusable abstractions to consume and transform values from a wide range of concrete enumerable collections such as arrays, lists, database tables, and XML documents. Similarly, Rx allows programmers to glue together complex event processing and asynchronous computations using LINQ queries over observable collections such as .NET events and APM-based computations, PFx concurrent Task&#60;T&#62;,  the Windows 7 Sensor and Location APIs, SQL StreamInsight temporal event streams , F# first-class events, and async workflows.</p>
<p>Play with Rx, stress it, evaluate it, and tell us what you think.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[My Intro to Functional Programming]]></title>
<link>http://silentzephyr.wordpress.com/2009/11/14/my-intro-to-functional-programming/</link>
<pubDate>Sat, 14 Nov 2009 23:49:31 +0000</pubDate>
<dc:creator>silentzephyr</dc:creator>
<guid>http://silentzephyr.wordpress.com/2009/11/14/my-intro-to-functional-programming/</guid>
<description><![CDATA[Wrote some &#8220;functions&#8221; in Function Programming (FP) the other day. Interesting, to say t]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Wrote some &#8220;functions&#8221; in Function Programming (FP) the other day. Interesting, to say the least. It was for a class but it was really my first hands on experience with a functional language.</p>
<p>Although there is an interpreter for this language, it isn&#8217;t as developed as it could be and it definitely needs a debugger. Anyway, interesting first experience.</p>
<p>Now onto Haskell. Oh fun. At least there&#8217;s a huge amount of documentation and books on how to program in Haskell =) It&#8217;s always good to have resources. Will write more about it when I know what I&#8217;m doing!</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Clojure Changing My Mind]]></title>
<link>http://invisibleblocks.wordpress.com/2009/11/13/clojure-changing-my-mind/</link>
<pubDate>Fri, 13 Nov 2009 22:15:17 +0000</pubDate>
<dc:creator>Daniel Bernier</dc:creator>
<guid>http://invisibleblocks.wordpress.com/2009/11/13/clojure-changing-my-mind/</guid>
<description><![CDATA[As good as Processing is, it&#8217;s still java. I&#8217;ve slowly been learning clojure, and trying]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>As good as <a href="http://processing.org">Processing</a> is, it&#8217;s still java.  I&#8217;ve slowly been learning <a href="http://clojure.org">clojure</a>, and trying to use it with Processing, via <a href="http://github.com/rosado/clj-processing">clj-processing</a>. While <a href="http://clojure.org/Reference">the clojure docs</a> and <a href="http://www.amazon.com/gp/product/1934356336?ie=UTF8&#38;tag=invisblock-20&#38;linkCode=as2&#38;camp=1789&#38;creative=390957&#38;creativeASIN=1934356336">the book</a> are both good, I&#8217;m still in that flounder-around stage, trying out tiny experiments to understand how things work.</p>
<p>I wanted a function to make saw-step sequences: (1 2 3 2 1 2 3 2 &#8230;).  You give it the low bound, the high bound, and the step-size.  For example:</p>
<ul>
<li><code>(saw-step 1 4 1)</code> gives <code>(1 2 3 4 3 2 1 2 3 4 3 ...)</code></li>
<li><code>(saw-step 0 15 5)</code> gives <code>(0 5 10 15 10 5 0 5 ...)</code></li>
<li><code>(saw-step 0 5 2)</code> gives <code>(0 2 4 5 3 1 0 2 4 5 ...)</code></li>
</ul>
<p>I&#8217;ve coded this kind of thing up in ruby, javascript, or java a dozen times, though it&#8217;s usually inside a loop, not returning a list.  Something like this:</p>
<pre class="brush: jscript;">
var min = 3;
var max = 7;
var step = 2;

var n = min;
while(shouldContinue()) {
    doSomethingWith(n);
    n += step;
    if (n+step &#62; max &#124;&#124; n-step &#60; min) {
        step *= -1;  // turn around
    }
}
</pre>
<p>My first try in clojure took a similar tack.  I never got it right, but it was something like this:</p>
<pre style="font-size:1.2em;">(defn saw-step
  [min max step-size]
    (let [step (ref step-size)]
      (iterate
       (fn [x]
         (if (or ( min (- x @step)))
           (dosync (alter step -)))
         (+ @step x))
         min)))</pre>
<p>It&#8217;s a disaster &#8212; the parentheses don&#8217;t even match &#8212; but you get the gist.  I was trying to cram the same imperative algorithm into clojure: keep some mutable state, add <code>step</code> to it, and when you reach the edges, mutate <code>step</code> to change direction.  I kept getting bugs where it would go one step beyond the edge, or it would start working its way back from one edge, only to turn around again, and bounce against the edge forever.</p>
<p>I gave up and went to bed, but a few days later, I had better luck.</p>
<pre style="font-size:1.2em;">(defn saw-step
  [min max step]
     (cycle
      (into (vec (range min max step)) ; vec, so (into) adds to end
	    (for [x
		  (iterate #(- % step) max)
		  :while (&#62; x min)] x))))</pre>
<p>The first not-entirely-wrong step I made was to try breaking the list of numbers I wanted into two parts: the going-up numbers, and the coming-down numbers.  (0 2 4 5 3 1) is just (0 2 4) + (5 3 1).  The <code>(range min max step)</code> part gives you the going-ups, and the <code>(for [x (iterate ...)</code> stuff is the going-downs, as a list comprehension.</p>
<p>(One mistake I made was trying <code>(range max min step)</code> for the going-downs, which yields an empty list; another was using <code>(iterate dec max)</code>, which never ends, because it keeps decrementing into the negatives.  I found my way out with the list comprehension, but I bet there&#8217;s a better way.)</p>
<p>Once you have those two lists, you can use <code>into</code> to add each item from the second list to the first, giving you (0 2 4 5 3 1).  That goes into <code>cycle</code> for a lazy, infinite sequence.</p>
<p>The solution&#8217;s not too bad: a saw-step is a cycle of the going-ups, followed by the going-downs.  The code looks about that way.</p>
<p>(It occurred to me after that I could always use a default step of 1, and pipe the result through a scaling map.  That would give me the bounds I wanted, with the extra benefit of evenly-spaced steps.  Maybe I&#8217;ll remove <code>step</code> later.)</p>
<p><a href="http://www.cs.yale.edu/quotes.html">Alan Perlis</a> said, &#8220;A language that doesn&#8217;t affect the way you think about programming, is not worth knowing.&#8221;  He also said, &#8220;The only difference(!) between Shakespeare and you was the size of his idiom list &#8211; not the size of his vocabulary.&#8221;  Clojure&#8217;s changing my mind, a bit at a time.</p>
<p><em> </em></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Considering Adding a Functional Language to My Bag of Tricks]]></title>
<link>http://goldmanalpha.wordpress.com/2009/11/13/functionallanguage/</link>
<pubDate>Fri, 13 Nov 2009 16:51:42 +0000</pubDate>
<dc:creator>goldmanalpha</dc:creator>
<guid>http://goldmanalpha.wordpress.com/2009/11/13/functionallanguage/</guid>
<description><![CDATA[There are a lot of people @Lab who know things like Erlang, Haskell, Python, R, etc., etc., etc.  I]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>There are a lot of people <a href="http://www.lab49.com/" target="_blank">@Lab</a> who know things like <a href="http://www.erlang.org/index.html" target="_blank">Erlang</a>, <a href="http://www.haskell.org/" target="_blank">Haskell</a>, <a href="http://www.python.org/" target="_blank">Python</a>, <a href="http://www.r-project.org/" target="_blank">R</a>, etc., etc., etc.  I&#8217;m actually considering learning <a href="http://en.wikiquote.org/wiki/Lisp_programming_language">Lisp</a>, but I need a project.  I &#8220;learned&#8221; <a href="http://www.sitepoint.com/forums/showthread.php?t=155043" target="_blank">php</a> for a project over the summer, but I didn&#8217;t really like it since its so much like classic ASP (really messy).  Maybe I&#8217;ll learn <a href="http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/" target="_blank">F#</a> instead&#8230;  That shouldn&#8217;t be such a strech since I built an <a href="http://www.csis.pace.edu/%7Ebergin/compiler/CompilerAward.html">ML compiler</a> in grad school (F# is based on ML).  I wonder what kind of project I’d be interested in would benefit from a functional language&#8230;  I suppose I’ll have to read up on the language and maybe that will give me some ideas.</p>
<p>Its funny, doing WPF, my umpteenth technology, is just not enough.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Open Source in Finance eXchange: December 15]]></title>
<link>http://skillsmatterblog.wordpress.com/2009/11/09/open-source-in-finance-exchange-december-15/</link>
<pubDate>Mon, 09 Nov 2009 17:07:56 +0000</pubDate>
<dc:creator>Skills Matter</dc:creator>
<guid>http://skillsmatterblog.wordpress.com/2009/11/09/open-source-in-finance-exchange-december-15/</guid>
<description><![CDATA[Places are going fast for this year&#8217;s Open Source in Finance eXchange on December 15.  Speakin]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p style="text-align:center;"><a href="http://skillsmatter.com/event/design-architecture/open-source-in-finance-exchange/js-432"><img class="aligncenter size-full wp-image-19" title="open-source-in-finance-456x100" src="http://skillsmatterblog.wordpress.com/files/2009/11/open-source-in-finance-456x1001.gif" alt="open-source-in-finance-456x100" width="450" height="98" /></a></p>
<p>Places are going fast for this year&#8217;s Open Source in Finance eXchange on December 15.  Speaking across six expert talks and two parkbench discussions on the day will be Alan  Hardy, Rob Davies, Angelo Corsaro and David Vincent.</p>
<p>This year&#8217;s eXchange is bringing together the leading experts in Open Source technology and Financial Services software development with innovators, technologists, architects and developers in the developer community.</p>
<p>The day promises to combine deep technical insight with friendly discussion around creating highly scalable, secure systems and leveraging OS technology within the finance sector.</p>
<p>The programme is structured to encourage discussion and bring together the leading thinkers and experts on the use open source technology in Financial Services with passionate members of the developer community in this sector.</p>
<p>To keep it as informal as possible we are strictly limiting the event to 125 delegates, and it is already proving to be popular.  What&#8217;s more, on the day we will be raffling off a ticket to this year&#8217;s QCon in London.</p>
<p><strong>Book now &#8212; and get your tickets for </strong><strong><strong>£65.  Just click the banner at the top of the page.</strong><br />
</strong></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[F# Tutorial]]></title>
<link>http://mikevallotton.wordpress.com/2009/11/03/f-tutorial/</link>
<pubDate>Tue, 03 Nov 2009 23:06:00 +0000</pubDate>
<dc:creator>mikevallotton</dc:creator>
<guid>http://mikevallotton.wordpress.com/2009/11/03/f-tutorial/</guid>
<description><![CDATA[Here&#8217;s a great tutorial on F# written from the perspective of a developer already comfortable ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Here&#8217;s a great <a href="http://www.jelovic.com/weblog/?p=215">tutorial on F#</a> written from the perspective of a developer already comfortable with C#.  I&#8217;m just starting to play around with some functional development, and as this is a great jumping off point for someone that wants a quick introduction to F#, I thought I&#8217;d share.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[On Lisp]]></title>
<link>http://sidhantgodiwala.wordpress.com/2009/11/02/on-lisp/</link>
<pubDate>Sun, 01 Nov 2009 18:51:32 +0000</pubDate>
<dc:creator>Sidhant Godiwala</dc:creator>
<guid>http://sidhantgodiwala.wordpress.com/2009/11/02/on-lisp/</guid>
<description><![CDATA[Another project i&#8217;m working on is translating Paul Graham&#8217;s On Lisp (which is available ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Another project i&#8217;m working on is translating Paul Graham&#8217;s O<a title="On Lisp" href="http://www.paulgraham.com/onlisp.html">n Lisp </a> (which is available for free) into Clojure, well some of it anyway.</p>
<p>It&#8217;s really fun and interesting to read a book by graham since his <a title="Essays" href="http://www.paulgraham.com/articles.html">essays </a>inspired me to learn Lisp in the first place. As with the project Euler sums, i&#8217;ll post more info as I discover it</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[It's coming]]></title>
<link>http://dutherenverseauborddelatable.wordpress.com/2009/11/01/its-coming/</link>
<pubDate>Sun, 01 Nov 2009 12:08:40 +0000</pubDate>
<dc:creator>yoric</dc:creator>
<guid>http://dutherenverseauborddelatable.wordpress.com/2009/11/01/its-coming/</guid>
<description><![CDATA[And it can change the face of the web. Honest. &nbsp; Stay tuned&#8230;]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>And it can change the face of the web. Honest.</p>
<p>&#160;</p>
<p>Stay tuned&#8230;</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Quick introduction to functions in Scala]]></title>
<link>http://jcranky.wordpress.com/2009/10/29/quick-introduction-to-functions-in-scala/</link>
<pubDate>Thu, 29 Oct 2009 22:38:35 +0000</pubDate>
<dc:creator>Paulo Renato</dc:creator>
<guid>http://jcranky.wordpress.com/2009/10/29/quick-introduction-to-functions-in-scala/</guid>
<description><![CDATA[So, as you might already know, Scala is a functional language. This means that it is heavily based o]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>So, as you might already know, <em>Scala</em> is a functional language. This means that it is heavily based on functions (<em>Scala</em> actually mixes <em>Object Orientation</em> and <em>Functional Programming</em>).</p>
<p>Lets take a look on how to use functions in <em>Scala</em>. It is really fun, after you get the feel for it.</p>
<p>First, you must know that in <em>Scala</em>, almost (if not) everything can be used as a function identifier. An example:</p>
<pre class="brush: java;">
1.+(2)
</pre>
<p>This will  result in, obviously, <em>3</em>. It is even like <em>Scala</em> had operator overload, except that <strong>+</strong>, <strong>-</strong>, <strong>/</strong> and <strong>*</strong> are not exactly operators in <em>Scala</em>. They are functions, like everything else. Take a look at the <a title="scaladoc for class Int" href="http://www.scala-lang.org/docu/files/api/scala/Int.html" target="_blank"><em>scaladoc</em> for the Int class</a>, and notice all the functions for those operators.</p>
<p>Of course, the code above is really ugly. So you should write it like this:</p>
<pre class="brush: java;">
1 + 2
</pre>
<p>and the <em>Scala</em> compiler takes care of transforming it to the previous example. And what&#8217;s more: this is <em>not</em> any kind of special case. This is valid for any function. So, instead of writing this:</p>
<pre class="brush: java;">
calculator.sum(2,3)
</pre>
<p>you could write this:</p>
<pre class="brush: java;">
calculator sum(2,3)
</pre>
<p>Dumb example, but nice anyway, isn&#8217;t it?</p>
<p>Something more interesting now. If you are used to <em>Javascript</em>, you are used to sometimes pass functions around to other functions. <em>Scala</em> allows us to do the same thing:</p>
<pre class="brush: java;">
def operationTest(operation: (Float, Float) =&#62; Float): Float = {
    operation(5,3)
}
</pre>
<p>The code above declares a function, <em>operationTest</em>, that receives another function, <em>operation</em>, which receives two <em>Float</em>s and returns a <em>Float</em> as well.</p>
<p>The <em>operationTest</em> function then calls the function it received. The result of <em>operationTest</em> is whatever results from <em>operation</em> &#8211; in <em>Scala</em>, the return value of a function is always the result of the last statement in it.</p>
<p>You can exercise <em>operationTest</em> this way:</p>
<pre class="brush: java;">
// returns 8.0
operationTest( (x: Float, y: Float) =&#62; x + y )

// returns 2.0
operationTest( (x: Float, y: Float) =&#62; x - y )

// returns 1.66666666
operationTest( (x: Float, y: Float) =&#62; x / y )

// returns 15.0
operationTest( (x: Float, y: Float) =&#62; x * y )
</pre>
<p>So in the code above, we are declaring anonymous functions and passing them to <em>operationTest</em>, which then executes whatever function it received.</p>
<p>Here,<em> (x: Float, y: Float)</em> is the function header, or declaration, and everything after<em> =&#62;</em> is the function body: <em>x + y</em>, <em>x &#8211; y</em>, <em>x / y</em> and <em>x * y</em> in these cases. Notice also that we are not declaring the functions&#8217; return types. <em>Scala</em> infers them from the execution of the body, and thus from the type of the parameters.</p>
<p>That&#8217;s it for now. Willing to learn something in specific about <em>Scala</em>? Post a comment and let me know! I&#8217;m in the quest for mastering this language, so challanges are much appreciated! =)</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Haskell/C++ Video and Slides]]></title>
<link>http://bartoszmilewski.wordpress.com/2009/10/26/haskellc-video-and-slides/</link>
<pubDate>Mon, 26 Oct 2009 20:27:34 +0000</pubDate>
<dc:creator>Bartosz Milewski</dc:creator>
<guid>http://bartoszmilewski.wordpress.com/2009/10/26/haskellc-video-and-slides/</guid>
<description><![CDATA[The video of my talk, Haskell and C++ Template Metaprogramming, is now available; and so are the sli]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>The video of my talk, <a href="http://vimeo.com/7211030">Haskell and C++ Template Metaprogramming</a>, is now available; and so are the <a href="http://www.nwcpp.org/Downloads/2009/Haskell_and_C___Template.pdf">slides</a>. I pretty much covered the material from my last <a href="http://bartoszmilewski.wordpress.com/2009/10/21/what-does-haskell-have-to-do-with-c/">blog post</a>, but many people (including me) find a video presentation easier to follow. </p>
<p>This is also a plug for the <a href="http://www.nwcpp.org">Northwest C++ Users Group</a> that meets in Redmond every third Wednesday of the month. If you live in Seattle or on the east side of Lake Washington, check it out. You won&#8217;t be disappointed. </p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Haskell jobs]]></title>
<link>http://mostlycode.wordpress.com/2009/10/26/haskell-jobs/</link>
<pubDate>Mon, 26 Oct 2009 09:59:53 +0000</pubDate>
<dc:creator>Tener</dc:creator>
<guid>http://mostlycode.wordpress.com/2009/10/26/haskell-jobs/</guid>
<description><![CDATA[Recently I&#8217;ve been looking for a job involving Haskell or functional programming in general. N]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Recently I&#8217;ve been looking for a job involving Haskell or functional programming in general. No luck. I know that there are is <a href="http://www.haskell.org/haskellwiki/Jobs">page</a> in Haskell wiki about that, but it&#8217;s almost empty, if I filter out those which doesn&#8217;t match my preferences.</p>
<p>First thing is: most companies are from US. Next came UK finance companies (like Barclays or Credit Suisse), which are way too far for me. There are also a couple of links to now-dead startups that meant to use Haskell as a silver bullet. No luck I suppose. The one interesting company listed there is <a href="http://www.starling-software.com">Starling Software</a>. Too bad they are from Japan. Another notable exception is <i><a href="http://erlang-consulting.com/">Erlang Training and Consulting Ltd</a></i>. Sadly, while they do have an office in <a href="http://maps.google.com/maps?f=q&#38;source=s_q&#38;hl=en&#38;geocode=&#38;q=krakow,+poland&#38;sll=37.0625,-95.677068&#38;sspn=47.483365,79.013672&#38;ie=UTF8&#38;hq=&#38;hnear=Cracow,+Krakow,+Lesser+Poland,+Poland&#38;z=11">Kraków</a>, they don&#8217;t seem to willing to expand their staff <a href="http://www.erlang-consulting.com/jobs/listing">there</a>.</p>
<p>I also tried several job search engines for a FP job in Poland, without luck.</p>
<p>My research seems to agree with a previous work you can read about <a href="http://mult.ifario.us/p/there-are-apparently-lots-of-haskell-jobs">here</a>.</p>
<p>It is sad that most companies that use FP seem to be either too far away or long dead.</p>
<p>I would really love to see one of those near <a href="http://maps.google.com/maps?f=q&#38;source=s_q&#38;hl=en&#38;geocode=&#38;q=wroc%C5%82aw,+poland&#38;sll=37.0625,-95.677068&#38;sspn=47.483365,79.013672&#38;ie=UTF8&#38;hq=&#38;hnear=Wroc%C5%82aw,+Wroclaw,+Lower+Silesia,+Poland&#38;t=h&#38;z=11">Wrocław</a>.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[C#: A Method for Tail Call Recursion]]></title>
<link>http://scmccart.wordpress.com/2009/10/22/c-a-method-for-tail-call-recursion/</link>
<pubDate>Thu, 22 Oct 2009 19:16:18 +0000</pubDate>
<dc:creator>scmccart</dc:creator>
<guid>http://scmccart.wordpress.com/2009/10/22/c-a-method-for-tail-call-recursion/</guid>
<description><![CDATA[I’ve been reading on F# a bit, and came across it’s ability to do tail call recursion. Tail recursio]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I’ve been reading on F# a bit, and came across it’s ability to do tail call recursion. Tail recursion as defined by <a href="http://en.wikipedia.org/wiki/Tail_recursion" target="_blank">Wikipedia</a>:</p>
<blockquote><p>In <a href="http://en.wikipedia.org/wiki/Computer_science">computer science</a>, tail recursion (or tail-end recursion) is a special case of <a href="http://en.wikipedia.org/wiki/Recursion_%28computer_science%29">recursion</a> in which the last operation of the function, the <a href="http://en.wikipedia.org/wiki/Tail_call">tail call</a>, is a recursive call. Such recursions can be easily transformed to iterations. Replacing recursion with <a href="http://en.wikipedia.org/wiki/Iteration">iteration</a>, manually or automatically, can drastically decrease the amount of <a href="http://en.wikipedia.org/wiki/Call_stack">stack</a> space used and improve efficiency. This technique is commonly used with <a href="http://en.wikipedia.org/wiki/Functional_programming">functional programming</a> languages, where the <a href="http://en.wikipedia.org/wiki/Declarative_programming">declarative approach</a> and explicit handling of <a href="http://en.wikipedia.org/wiki/State_%28computer_science%29">state</a> promote the use of recursive functions that would otherwise rapidly fill the <a href="http://en.wikipedia.org/wiki/Call_stack">call stack</a>.</p>
</blockquote>
<p>So, I decided to see if I could implement this in C#, and after a little bit of monkeying around I was able to get something working.</p>
<p>First off, I needed two helper classes, the first of which is the Ref&#60;T&#62; class. It makes it possible to keep track of a reference to an object across closures. There is also an implicit conversion back to the type it is referencing for convenience.
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:e3f514d1-6eec-416a-959d-d35e9f1f7b61" class="wlWriterEditableSmartContent">
<div style="border:#000080 1px solid;color:#000;font-family:'Courier New', Courier, Monospace;font-size:10pt;">
<div style="background-color:#ffffff;overflow:auto;white-space:nowrap;padding:2px 5px;"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> <span style="color:#2b91af;">Ref</span>&#60;T&#62;<br /> {<br /> &#160;&#160;&#160;&#160;<span style="color:#0000ff;">public</span> T Value { <span style="color:#0000ff;">get</span>; <span style="color:#0000ff;">set</span>; }</p>
<p> &#160;&#160;&#160;&#160;<span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">implicit</span> <span style="color:#0000ff;">operator</span> T(<span style="color:#2b91af;">Ref</span>&#60;T&#62; obj)<br /> &#160;&#160;&#160;&#160;{<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff;">return</span> obj.Value;<br /> &#160;&#160;&#160;&#160;}<br /> } </div>
</p></div>
</p></div>
</p>
<p> Next was the LazyRef&#60;T&#62;, which is the same as Ref&#60;T&#62; but won’t actually compute the value until it is needed.
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:b301fea4-1796-4579-95c6-dfa3e395c24e" class="wlWriterEditableSmartContent">
<div style="border:#000080 1px solid;color:#000;font-family:'Courier New', Courier, Monospace;font-size:10pt;">
<div style="background-color:#ffffff;overflow:auto;white-space:nowrap;padding:2px 5px;"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> <span style="color:#2b91af;">LazyRef</span>&#60;T&#62;<br /> {<br /> &#160;&#160;&#160;&#160;<span style="color:#0000ff;">public</span> T Value { <span style="color:#0000ff;">get</span> { <span style="color:#0000ff;">return</span> Factory(); } }<br /> &#160;&#160;&#160;&#160;<span style="color:#0000ff;">public</span> <span style="color:#2b91af;">Func</span>&#60;T&#62; Factory { <span style="color:#0000ff;">get</span>; <span style="color:#0000ff;">set</span>; }</p>
<p> &#160;&#160;&#160;&#160;<span style="color:#0000ff;">public</span> LazyRef()<br /> &#160;&#160;&#160;&#160;{<br /> &#160;&#160;&#160;&#160;}</p>
<p> &#160;&#160;&#160;&#160;<span style="color:#0000ff;">public</span> LazyRef(<span style="color:#2b91af;">Func</span>&#60;T&#62; factory)<br /> &#160;&#160;&#160;&#160;{<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff;">this</span>.Factory = factory;<br /> &#160;&#160;&#160;&#160;}</p>
<p> &#160;&#160;&#160;&#160;<span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">implicit</span> <span style="color:#0000ff;">operator</span> T(<span style="color:#2b91af;">LazyRef</span>&#60;T&#62; obj)<br /> &#160;&#160;&#160;&#160;{<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff;">return</span> obj.Value;<br /> &#160;&#160;&#160;&#160;}</p>
<p> &#160;&#160;&#160;&#160;<span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">implicit</span> <span style="color:#0000ff;">operator</span> <span style="color:#2b91af;">LazyRef</span>&#60;T&#62;(T obj)<br /> &#160;&#160;&#160;&#160;{<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff;">return</span> <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">LazyRef</span>&#60;T&#62;(() =&#62; obj);<br /> &#160;&#160;&#160;&#160;}<br /> } </div>
</p></div>
</p></div>
</p>
<p> Alright, now all that remains is the method that does all of the magic, I’ll present it piecewise then all together at the end. First, let’s look at the method’s signature,
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:9ce6054a-6443-401a-bc3e-58141d2f1541" class="wlWriterEditableSmartContent">
<div style="border:#000080 1px solid;color:#000;font-family:'Courier New', Courier, Monospace;font-size:10pt;">
<div style="background-color:#ffffff;overflow:auto;white-space:nowrap;padding:2px 5px;"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#2b91af;">Func</span>&#60;T, R&#62; ToTailCall&#60;T, R&#62;(<br /> &#160;&#160;&#160;&#160;<span style="color:#0000ff;">this</span> <span style="color:#2b91af;">Func</span>&#60;<span style="color:#2b91af;">Func</span>&#60;T, <span style="color:#2b91af;">LazyRef</span>&#60;R&#62;&#62;, T, <span style="color:#2b91af;">LazyRef</span>&#60;R&#62;&#62; target) </div>
</p></div>
</p></div>
</p>
<p>It will return a delegate that represents the tail call optimized method, taking a T as the only parameter and returning an R. The only argument is the target method/delegate to be transformed. Note that the target takes a delegate as it’s first argument, this will be the recurse function that the method will call instead of itself when it wishes to proceed. It then takes a T, and returns a LazyRef to an R.</p>
<p>Now for the first part of the method, just some Ref and LazyRef variables, I’ll explain these as they are used.
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:5e4953cc-cf28-4c12-820f-4d66d7d4e964" class="wlWriterEditableSmartContent">
<div style="border:#000080 1px solid;color:#000;font-family:'Courier New', Courier, Monospace;font-size:10pt;">
<div style="background-color:#ffffff;overflow:auto;white-space:nowrap;padding:2px 5px;"><span style="color:#0000ff;">var</span> calledRef = <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">Ref</span>&#60;<span style="color:#0000ff;">bool</span>&#62;();<br /> <span style="color:#0000ff;">var</span> paramRef = <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">Ref</span>&#60;T&#62;();<br /> <span style="color:#0000ff;">var</span> currResult = <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">Ref</span>&#60;<span style="color:#2b91af;">LazyRef</span>&#60;R&#62;&#62;();<br /> <span style="color:#0000ff;">var</span> lazyResult = <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">LazyRef</span>&#60;R&#62;(<br /> &#160;&#160;&#160;&#160;() =&#62; currResult.Value.Value); </div>
</p></div>
</p></div>
</p>
<p>Next up is setRef, it’s the function that will be the recurse function that is passed in as the first argument when target is called.
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:9c52b83a-fe1d-4b7d-a070-bb226f6af649" class="wlWriterEditableSmartContent">
<div style="border:#000080 1px solid;color:#000;font-family:'Courier New', Courier, Monospace;font-size:10pt;">
<div style="background-color:#ffffff;overflow:auto;white-space:nowrap;padding:2px 5px;"><span style="color:#2b91af;">Func</span>&#60;T, <span style="color:#2b91af;">LazyRef</span>&#60;R&#62;&#62; setRef = t =&#62; {<br /> &#160;&#160;&#160;&#160;calledRef.Value = <span style="color:#0000ff;">true</span>;<br /> &#160;&#160;&#160;&#160;paramRef.Value = t;<br /> &#160;&#160;&#160;&#160;<span style="color:#0000ff;">return</span> lazyResult;<br /> }; </div>
</p></div>
</p></div>
</p>
<p>setRef first flips the calledRef flag, so that we know that target wants to do one more recursion, then we store off the value that target wanted to pass on, and we return the lazyResult. lazyResult will return currResult’s value when asked what it’s value is.</p>
<p>Next, is the actual function that is returned,
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:0a0d24b2-6eab-4a91-8b85-55d13f441193" class="wlWriterEditableSmartContent">
<div style="border:#000080 1px solid;color:#000;font-family:'Courier New', Courier, Monospace;font-size:10pt;">
<div style="background-color:#ffffff;overflow:auto;white-space:nowrap;padding:2px 5px;"><span style="color:#0000ff;">return</span> t =&#62; {<br /> &#160;&#160;&#160;&#160;paramRef.Value = t;</p>
<p> &#160;&#160;&#160;&#160;<span style="color:#0000ff;">do</span><br /> &#160;&#160;&#160;&#160;{<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;calledRef.Value = <span style="color:#0000ff;">false</span>;<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;currResult.Value = target(setRef, paramRef.Value);<br /> &#160;&#160;&#160;&#160;} <span style="color:#0000ff;">while</span> (calledRef.Value);</p>
<p> &#160;&#160;&#160;&#160;<span style="color:#0000ff;">return</span> lazyResult.Value;<br /> }; </div>
</p></div>
</p></div>
</p>
<p>First off, it sets up the current parameter value as t, since it needs to be set for the first iteration. Then it enters the loop and flips the calledRef flag to false, so if target doesn’t call the recurse function the loop will not continue. After that target is called, passing in setRef as the recurse function, and the current parameter value. It’s return is stored as the currentResult which will be lazyResult until target doesn’t call the recurse function, at which point it will return something else. This goes on until target doesn’t call the recurse function and the loop exits. After that we return the value or lazyResult, which is the value or currentResult. Ok, so here is everything all together:</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:6dcec1eb-adff-4e0c-ba45-ab613b1d67ea" class="wlWriterEditableSmartContent">
<div style="border:#000080 1px solid;color:#000;font-family:'Courier New', Courier, Monospace;font-size:10pt;">
<div style="background-color:#ffffff;overflow:auto;white-space:nowrap;padding:2px 5px;"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">class</span> <span style="color:#2b91af;">Recursion</span><br /> {<br /> &#160;&#160;&#160;&#160;<span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#2b91af;">Func</span>&#60;T, R&#62; ToTailCall&#60;T, R&#62;(<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff;">this</span> <span style="color:#2b91af;">Func</span>&#60;<span style="color:#2b91af;">Func</span>&#60;T, <span style="color:#2b91af;">LazyRef</span>&#60;R&#62;&#62;, T, <span style="color:#2b91af;">LazyRef</span>&#60;R&#62;&#62; target)<br /> &#160;&#160;&#160;&#160;{<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff;">var</span> calledRef = <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">Ref</span>&#60;<span style="color:#0000ff;">bool</span>&#62;();<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff;">var</span> paramRef = <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">Ref</span>&#60;T&#62;();<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff;">var</span> currResult = <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">Ref</span>&#60;<span style="color:#2b91af;">LazyRef</span>&#60;R&#62;&#62;();<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff;">var</span> lazyResult = <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">LazyRef</span>&#60;R&#62;(<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;() =&#62; currResult.Value.Value);</p>
<p> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#2b91af;">Func</span>&#60;T, <span style="color:#2b91af;">LazyRef</span>&#60;R&#62;&#62; setRef = t =&#62; {<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;calledRef.Value = <span style="color:#0000ff;">true</span>;<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;paramRef.Value = t;<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff;">return</span> lazyResult;<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;};</p>
<p> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff;">return</span> t =&#62; {<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;paramRef.Value = t;</p>
<p> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff;">do</span><br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;{<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;calledRef.Value = <span style="color:#0000ff;">false</span>;<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;currResult.Value = target(setRef, paramRef.Value);<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;} <span style="color:#0000ff;">while</span> (calledRef.Value);</p>
<p> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff;">return</span> lazyResult.Value;<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;};<br /> &#160;&#160;&#160;&#160;}<br /> } </div>
</p></div>
</p></div>
<p>&#160;</p>
<p>All of the refs end up in closures in either setRef or the return value, so the values they reference can be shared and changed. Having the current result be lazy in itself makes the whole thing possible. If we didn’t have LazyRef target would be expecting a computed value to be returned from recurse which would require actual recursion.</p>
<p>Time for a quick example, this will run until the x overflows:</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:40e36219-3c7a-4a36-8ee5-879f66e12821" class="wlWriterEditableSmartContent">
<div style="border:#000080 1px solid;color:#000;font-family:'Courier New', Courier, Monospace;font-size:10pt;">
<div style="background-color:#ffffff;overflow:auto;white-space:nowrap;padding:2px 5px;"><span style="color:#0000ff;">static</span> <span style="color:#0000ff;">void</span> Main(<span style="color:#0000ff;">string</span>[] args)<br /> {<br /> &#160;&#160;&#160;&#160;<span style="color:#0000ff;">var</span> tailFoo = <span style="color:#2b91af;">Recursion</span>.ToTailCall&#60;<span style="color:#0000ff;">int</span>, <span style="color:#0000ff;">int</span>&#62;((recurse, x) =&#62; {<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff;">try</span><br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;{<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#2b91af;">Console</span>.WriteLine(x);</p>
<p> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff;">return</span> recurse(x + <span style="color:#a52a2a;">1</span>);<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;}<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff;">catch</span> (<span style="color:#2b91af;">OverflowException</span>)<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;{<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff;">return</span> x;<br /> &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;}<br /> &#160;&#160;&#160;&#160;});</p>
<p> &#160;&#160;&#160;&#160;<span style="color:#2b91af;">Console</span>.WriteLine(<span style="color:#a31515;">&#8220;Done, {0} was the result.&#8221;</span>, tailFoo(<span style="color:#a52a2a;">0</span>));<br /> &#160;&#160;&#160;&#160;<span style="color:#2b91af;">Console</span>.ReadLine();&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<br /> } </div>
</p></div>
</p></div>
<p>&#160;</p>
<p>Feel free to post questions and comments.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[What Does Haskell Have to Do with C++?]]></title>
<link>http://bartoszmilewski.wordpress.com/2009/10/21/what-does-haskell-have-to-do-with-c/</link>
<pubDate>Wed, 21 Oct 2009 23:02:33 +0000</pubDate>
<dc:creator>Bartosz Milewski</dc:creator>
<guid>http://bartoszmilewski.wordpress.com/2009/10/21/what-does-haskell-have-to-do-with-c/</guid>
<description><![CDATA[If you want to understand C++ template metaprogramming (TMP) you have to know functional programming]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>If you want to understand C++ template metaprogramming (TMP) you have to know functional programming. Seriously. I want you to think of TMP as maximally obfuscated (subset of) Haskell, and I&#8217;ll illustrate this point by point. If you don&#8217;t know Haskell, don&#8217;t worry, I&#8217;ll explain the syntax as I go. </p>
<p>The nice thing about single-paradigm languages like Haskell is that they have very simple syntax (think of Lisp that does everything with just a bunch of parentheses). I will start the Haskell-C++TMP mapping with basics, like functions and recursion, but I&#8217;ll try to cover a lot more, including higher-order functions, pattern matching, list comprehension (did you know it was expressible in C++?), and more. </p>
<p>Keep in mind that my Haskell examples are runtime functions operating on runtime data whereas their C++ TMP equivalents are compile-time templates operating mostly on types. Operation on types are essential in providing correct and efficient implementations of parametrized classes and functions. </p>
<p>By necessity the examples are simple, but the same mapping may be applied to much more complex templates from the C++ Standard Library and Boost. As a bonus, I&#8217;ll also explain the hot new thing, variadic templates.</p>
<h2>Functional Approach to Functions</h2>
<p>How do you implement useful functions if you don&#8217;t have mutable variables, <var>if</var> statements, or loops? To a C++ programmer that might seem like an impossible task. But that&#8217;s the reality of C++ compile-time language that forms the basis of TMP. Functional programming to the rescue! </p>
<p>As a warm-up, let&#8217;s see how Haskell implements a simple function, the factorial:</p>
<pre>fact 0 = 1
fact n = n * fact (n - 1)</pre>
<p>The first line states that the factorial of zero is one. The second line defines factorial for a non-zero argument, n (strictly speaking it only works for positive non-zero arguments). It does it using recursion: factorial of <var>n</var> is equal to <var>n</var> times the factorial of <var>n-1</var>. The recursion stops when <var>n</var> is equal to zero, in which case the first definition kicks in. Notice that the definition of the function <var>fact</var> is split into two sub-definitions. So when you call:</p>
<pre>fact 4</pre>
<p>the first definition is looked up first and, if it doesn&#8217;t match the argument (which it doesn&#8217;t), the second one comes into play. This is the simplest case of <i>pattern matching</i>: 4 doesn&#8217;t match the &#8220;pattern&#8221; 0, but it matches the pattern <var>n</var>.</p>
<p>Here&#8217;s almost <i>exactly</i> the same code expressed in C++ TMP:</p>
<pre>template<span style="color:#00f;">&#60;int n&#62;</span> struct
<span style="color:#00f;">fact</span> {
    static const int value = <span style="color:#00f;">n * fact&#60;n - 1&#62;</span>::value;
};

template&#60;&#62; struct
<span style="color:#00f;">fact&#60;0&#62;</span> { // specialization for n = 0
    static const int value = <span style="color:#00f;">1</span>;
};</pre>
<p>You might notice how the horrible syntax of C++ TMP obscures the simplicity and elegance of this code. But once you are equipped with the C++/Haskell decoder ring, things become a lot clearer. </p>
<p>Let&#8217;s analyze this code. Just like in Haskell, there are two definitions of <var>fact</var>, except that their order is inverted. This is because C++ requires template specialization to follow the template&#8217;s general definition (or declaration, as we&#8217;ll see later). The pattern matching of arguments in C++ does not follow the order of declarations but rather is based on &#8220;best match&#8221;. If you instantiate the template with argument zero:</p>
<pre>cout &#60;&#60; "Factorial of 0 = " &#60;&#60; fact&#60;0&#62;::value &#60;&#60; endl;</pre>
<p>the second pattern, <var>fact&#60;0&#62;</var>, is a better fit. Otherwise the first one, <var>&#60;int n&#62;</var>, is used.</p>
<p>Notice also the weird syntax for &#8220;function call&#8221;</p>
<pre>fact&#60;n&#62;::value</pre>
<p>and for the &#8220;return statement&#8221;</p>
<pre>static const int value = n * fact&#60;n - 1&#62;::value;</pre>
<p>This all makes sense if you look at templates as definitions of parameterized types, which was their initial purpose in C++. In that interpretation, we are defining a <var>struct</var> called <var>fact</var>, parameterized by an integer <var>n</var>, whose sole member is a static const integer called <var>value</var>. Moreover, this template is specialized for the case of <var>n</var> equal zero. </p>
<p>Now I want you to forget about what I just said and put on the glasses which make the C++ code look like the corresponding Haskell code. </p>
<p>Here&#8217;s another example&#8211;this time of a predicate (a function returning a Boolean):</p>
<pre>is_zero 0 = True
is_zero x = False</pre>
<p>Let&#8217;s spice it up a little for C++ and define a predicate on types rather than integers. The following compile-time function returns <var>true</var> only when the type <var>T</var> is a pointer:</p>
<pre>template&#60;class T&#62; struct
<span style="color:#00f;">isPtr</span> {
    static const bool value = false;
};

template&#60;class U&#62; struct
<span style="color:#00f;">isPtr&#60;U*&#62;</span> {
    static const bool value = true;
};</pre>
<p>This time the actual argument to <var>isPtr</var> is first matched to the more specialized pattern, <var>U*</var> and, if it fails, the general pattern is used. </p>
<p>We can add yet another specialization, which will pattern-match a const pointer:</p>
<pre>template&#60;class U&#62; struct
<span style="color:#00f;">isPtr&#60;U * const&#62;</span> {
    static const bool value = true;
};</pre>
<p>These types of type predicates may be, for instance, used to select more flexible and efficient implementations of parameterized containers. Think of the differences between a vector of values vs. a vector of pointers.</p>
<h2>Lists</h2>
<p>The basic data structure in functional languages is the list. Haskell&#8217;s lists are introduced using square brackets. For instance, a list of three numbers, 1, 2, 3, looks like:</p>
<pre>[1, 2, 3]</pre>
<p>List processing in functional languages follows the standard pattern: a list is split into <var>head</var> and <var>tail</var>, an operation is performed on the head, and the tail is processed using recursion. The splitting is done by pattern matching: the Haskell pattern being <var>(head:tail)</var> (to be precise, the colon in parentheses represents the <var>cons</var> operation&#8211;the creation of a list by prepending an element to an existing list). </p>
<p>Here&#8217;s a simple function, <var>count</var>, that calculates the length of a list:</p>
<pre>count [] = 0
count (head:tail) = 1 + count tail</pre>
<p>The first pattern, [], matches an empty list; the second a non-empty one. Notice that a function call in Haskell doesn&#8217;t use parentheses around arguments, so <var>count tail</var> is interpreted as a call to <var>count</var> with the argument <var>tail</var>.</p>
<p>Before C++0x, TMP was severely crippled by the lack of a list primitive. People used separate definitions for a list of zero, one, two, etc.,  elements, and even used special macros to define them. This is no longer true in C++0x, thanks to <i>variadic templates</i> and <i>template parameter packs</i>. Here&#8217;s our Haskel <var>count</var> translated into C++ TMP:</p>
<pre>// Just a declaration
template&#60;class... list&#62; struct
<span style="color:#00f;">count</span>;

template&#60;&#62; struct
<span style="color:#00f;">count&#60;&#62;</span> {
    static const int value = 0;
};

template&#60;class head, class... tail&#62; struct
<span style="color:#00f;">count&#60;head, tail...&#62;</span> {
    static const int value = 1 + count&#60;tail...&#62;::value;
};</pre>
<p>First we have a declaration (not a definition) of the template <var>count</var> that takes a variable number of type parameters (the keyword <var>class</var> or <var>typename</var> introduces a type parameter). They are packed into a template parameter pack, <var>list</var>. </p>
<p>Once this general declaration is visible, specializations may follow in any order. I arranged them to follow the Haskell example. The first one matches the empty list and returns zero. The second one uses the pattern, <var>&#60;head, tail&#8230;&#62;</var>. This pattern will match any non-empty list and split it into the <var>head</var> and the (possibly empty) <var>tail</var>. </p>
<p>To &#8220;call&#8221; a variadic template, you initiate it with an arbitrary number of arguments and retrieve its member, <var>value</var>, e.g.,</p>
<pre>int n = count&#60;int, char, long&#62;::value; // returns 3</pre>
<p>A few words about variadic templates: A variadic template introduces a template parameter pack using the notation <var>class&#8230; pack</var> (or <var>int&#8230; ipack</var>, etc&#8230;). The only thing you may do with a pack is to expand it and pass to another variadic template. The expansion is done by following the name of the pack with three dots, as in <var>tail&#8230;</var>. You&#8217;ll see more examples later.</p>
<p>Variadic templates have many applications such as type-safe printf, tuples (objects that store an arbitrary number of differently typed arguments), variants, and many more. </p>
<h2>Higher-Order Functions and Closures</h2>
<p>The real power of functional programming comes from treating functions as first class citizens. It means that you may pass functions to other functions and return functions from functions. Functions operating on functions are called higher-order functions. Surprisingly, it seems like compile-time C++ has better support for higher-order functions than run-time C++.</p>
<p>Let&#8217;s start with a Haskell example. I want to define a function that takes two predicate functions and returns another predicate function that combines the two using logical <var>OR</var>. Here it is in Haskell:</p>
<pre>or_combinator f1 f2 =
    &#955; x -&#62; (f1 x) &#124;&#124; (f2 x)</pre>
<p>The <var>or_combinator</var> returns an anonymous function (the famous &#8220;lambda&#8221;) that takes one argument, <var>x</var>, calls both <var>f1</var> and <var>f2</var> with it, and returns the logical <var>OR</var> of the two results. The return value of <var>or_combinator</var> is this freshly constructed function. I can then call this function with an arbitrary argument. For instance, here I&#8217;m checking if 2 is either zero or one (guess what, it isn&#8217;t!):</p>
<pre>(or_combinator is_zero is_one) 2</pre>
<p>I put the parentheses around the function and its arguments for readability, although they are not strictly necessary. 2 is the argument to the function returned by <var>or_combinator</var>. </p>
<p>The lambda that&#8217;s returned from <var>or_combinator</var> is actually a closure. It &#8220;captures&#8221; the two arguments, <var>f1</var> and <var>f2</var> passed to <var>or_combinator</var>. They may be used long after the call to <var>or_combinator</var> has returned. </p>
<p>It might take some getting used to it before you are comfortable with functions taking functions and returning functions, but it&#8217;s much easier to learn this stuff in Haskell than in the obfuscated C++. Indeed, here&#8217;s an almost direct translation of this example:</p>
<pre>template&#60;template&#60;class&#62; class <span style="color:#00f;">f1</span>, template&#60;class&#62; class <span style="color:#00f;">f2</span>&#62; struct
<span style="color:#00f;">or_combinator</span> {
    template&#60;class T&#62; struct
    <span style="color:#00f;">lambda</span> {
        static const bool value = <span style="color:#00f;">f1&#60;T&#62;</span>::value <span style="color:#00f;">&#124;&#124; f2&#60;T&#62;</span>::value;
    };
};</pre>
<p>Since in the metalanguage a function is represented by a template, the template <var>or_combinator</var> takes two such templates as arguments. It &#8220;calls&#8221; these templates using the standard syntax <var>f&#60;T&#62;::value</var>. Actually, the <var>or_combinator</var> doesn&#8217;t call these functions. Instead it defines a new template, which I call <var>lambda</var>, that takes the argument <var>T</var> and calls those functions. This template acts like a closure&#8211;it captures the two templates that are the arguments to <var>or_combinator</var>.</p>
<p>Here&#8217;s how you may use the <var>or_combinator</var> to combine two tests, <var>isPtr</var> and <var>isConst</var> and apply the result to the type <var>const int</var>:</p>
<pre>std::cout
   &#60;&#60; "or_combinator&#60;isPtr, isConst&#62;::lambda&#60;const int&#62;::value = "
   &#60;&#60; or_combinator&#60;isPtr, isConst&#62;::lambda&#60;const int&#62;::value
   &#60;&#60; std::endl;</pre>
<p>Such logical combinators are essential for predicate composability.</p>
<h2>Higher-Order Functions Operating on Lists</h2>
<p>Once you combine higher-order functions with lists you have a powerful functional language at your disposal. Higher-order functions operating on lists look very much like algorithms. Let me show you some classic examples. Here&#8217;s the function (or algorithm), <var>all</var>, that returns <var>true</var> if and only if all elements of a list satisfy a given predicate.</p>
<pre>all pred [] = True
all pred (head:tail) = (pred head) &#38;&#38; (all pred tail)</pre>
<p>By now you should be familiar with all the techniques I used here, like pattern matching or list recursion. </p>
<p>Here&#8217;s the same code obfuscated by the C++ syntax:</p>
<pre>template&#60;template&#60;class&#62; class predicate, class... list&#62; struct
<span style="color:#00f;">all</span>;

template&#60;template&#60;class&#62; class predicate&#62; struct
<span style="color:#00f;">all&#60;predicate&#62;</span> {
    static const bool value = true;
};

template&#60;
    template&#60;class&#62; class predicate,
    class head,
    class... tail&#62; struct
<span style="color:#00f;">all&#60;predicate, head, tail...&#62;</span> {
    static const bool value =
        predicate&#60;head&#62;::value
        &#38;&#38; all&#60;predicate, tail...&#62;::value;
};</pre>
<p>Except for the initial declaration required by C++ there is a one-to-one paradigm match between the two implementations. </p>
<p>Another useful algorithm, a veritable workhorse of functional programming, is &#8220;fold right&#8221; (together with it&#8217;s dual partner, &#8220;fold left&#8221;). It folds a list while accumulating the results (that&#8217;s why in runtime C++ this algorithm is called &#8220;accumulate&#8221;). Here&#8217;s the Haskell implementation:</p>
<pre>foldr f init [] = init
foldr f init (head:tail) =
    f head (foldr f init tail)</pre>
<p>Function <var>f</var>, which is the first argument to <var>foldr</var>, takes two arguments, the current element of the list and the accumulated value. Its purpose is to process the element and incorporate the result in the accumulator. The new accumulated value is then returned. It is totally up to the client to decide what kind of processing to perform, how it is accumulated, and what kind of value is used. The second argument, <var>init</var>, is the initial value for the accumulator.</p>
<p>Here&#8217;s how it works: The result of <var>foldr</var> is generated by acting with <var>f</var> on the head of the list and whatever has been accumulated by processing the tail of the list. The algorithm recurses until the tail is empty, in which case it returns the initial value. At runtime this type of algorithm would make N recursive calls before starting to pop the stack and accumulate the results. </p>
<p>For instance, <var>foldr</var> may be used to sum the elements of a list (<var>so_far</var> is the accumulator, which is initialized to zero):</p>
<pre>add_it elem so_far = elem + so_far
sum_it lst = foldr add_it 0 lst</pre>
<p>The accumulator function is <var>add_it</var>. If, instead, I wanted to calculate the product of all elements, I&#8217;d use a function <var>mult_it</var> and the starting value of one. You get the idea.</p>
<p>Here&#8217;s the same algorithm in C++ TMP:</p>
<pre>template&#60;template&#60;class, int&#62; class, int, class...&#62; struct
<span style="color:#00f;">fold_right</span>;

template&#60;template&#60;class, int&#62; class f, int init&#62; struct
<span style="color:#00f;">fold_right&#60;f, init&#62;</span> {
    static const int value = init;
};

template&#60;template&#60;class, int&#62; class f, int init, class head, class...tail&#62; struct
<span style="color:#00f;">fold_right&#60;f, init, head, tail...&#62;</span> {
    static const int value = f&#60;head, fold_right&#60;f, init, tail...&#62;::value&#62;::value;
};</pre>
<p>Once you understand the Haskell version, this complex code suddenly becomes transparent (if it doesn&#8217;t, try squinting <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />  ). </p>
<h2>Lists of Numbers</h2>
<p>Let&#8217;s now switch to integers for a moment. Haskell defines a function <var>sum</var> that adds all elements of a list:</p>
<pre>sum [] = 0
sum (head:tail) = head + (sum tail)</pre>
<p>We can do the same in C++ TMP (in five times as many lines of code):</p>
<pre>template&#60;int...&#62; struct
<span style="color:#00f;">sum</span>;

template&#60;&#62; struct
<span style="color:#00f;">sum&#60;&#62;</span> {
    static const int value = 0;
};

template&#60;int i, int... tail&#62; struct
<span style="color:#00f;">sum&#60;i, tail...&#62;</span> {
    static const int value = i + sum&#60;tail...&#62;::value;
};</pre>
<h2>List Comprehension</h2>
<p>Haskell has one more trick up its sleeve for operating on lists without explicit recursion. It&#8217;s called <i>list comprehension</i>. It&#8217;s a way of defining new lists based on existing lists. The nomenclature and notation are borrowed from Set Theory, where you often encounter definitions such as: S is a set of elements, where&#8230; Let&#8217;s look at a simple Haskell example:</p>
<pre>[x * x &#124; x &#60;- [3, 4, 5]]</pre>
<p>This is a set (list) of elements <var>x * x</var>, where <var>x</var> is from the list <var>[3, 4, 5]</var>. </p>
<p>Remember our recursive definition of <var>count</var>? Using list comprehension it&#8217;s reduced to a one-liner:</p>
<pre>count lst = sum [1 &#124; x &#60;- lst]</pre>
<p>Here, we create a list of ones, one for each element of the list. Our result is the sum of those ones. To make this definition more amenable to translation into C++, let&#8217;s define an auxiliary function <var>one</var> that, for any argument <var>x</var>, returns 1.</p>
<pre>one x = 1</pre>
<p>Here&#8217;s the modified definition of <var>count</var>:</p>
<pre>count lst = sum [one x &#124; x &#60;- lst]</pre>
<p>Now we are ready to convert this code to C++ TMP:</p>
<pre>template&#60;class T&#62; struct
<span style="color:#00f;">one</span> {
    static const int value = 1;
};

template&#60;class... lst&#62; struct
<span style="color:#00f;">count</span> {
    static const int value = sum&#60;one&#60;lst&#62;::value...&#62;::value;
};</pre>
<p>Here our list is stored in a template parameter pack, <var>lst</var>. If we wanted to expand this pack, we&#8217;d use the notation <var>lst&#8230;</var>, but that&#8217;s not what&#8217;s happening here. The ellipsis appears after the pattern containing the pack:</p>
<pre>one&#60;lst&#62;::value...</pre>
<p>Compare this with the equivalent Haskell:</p>
<pre>[one x &#124; x &#60;- lst]</pre>
<p>In C++, when the ellipsis follows a pattern that contains a pack, it&#8217;s not the pack that&#8217;s expanded, but the whole pattern is repeated for each element of the pack. Here, if our list were <var>&#60;int, char, void*&#62;</var>, the pattern would be expanded to:</p>
<pre>&#60;one&#60;int&#62;::value, one&#60;char&#62;::value, one&#60;void*&#62;::value&#62;</pre>
<p>The subsequent call to <var>sum</var> would be made with those arguments. </p>
<p>Notice that a different positioning of the ellipsis would result in a completely different expansion. This pattern:</p>
<pre>one&#60;lst...&#62;::value</pre>
<p>would result in the call to <var>one</var> with the list of types, which would be an error.</p>
<p>Here&#8217;s another example of pattern expansion: a function that counts the number of pointers in a list of types:</p>
<pre>template&#60;class... lst&#62; struct
<span style="color:#00f;">countPtrs</span> {
    static const int value = sum&#60;isPtr&#60;lst&#62;::value ...&#62;::value;
};</pre>
<p>In this case the pattern is:</p>
<pre>isPtr&#60;lst&#62;::value ...</pre>
<p>and it expands into a list of Booleans. (I&#8217;m taking advantage of the fact that <var>false</var> is zero and <var>true</var> is one, when converted to integers.)</p>
<p>You may find a more complex practical example in the Gregor, J&#228;rvi, and Powell paper (see bibliography).</p>
<h2>Continuations</h2>
<p>List comprehension can be used to define some very useful higher-order functions. One of such functions is <var>map</var>, which takes a list and applies a unary function to each element, resulting in a new list. You might be familiar with the runtime implementation of this algorithm in C++ STL under the name of <var>transform</var>. This is what <var>map</var> looks like in Haskell:</p>
<pre>map f lst = [f x &#124; x &#60;- lst]</pre>
<p>Here, <var>f</var> is the unary function and <var>lst</var> is the input list. You have to admire the terseness and elegance of this notation. </p>
<p>The first impulse would be to translate it into C++ TMP as:</p>
<pre>template&#60;template&#60;class&#62; class f, class... lst&#62; struct
<span style="color:#00f;">map</span> {
    typedef f&#60;lst&#62;... type;
};</pre>
<p>This is surprisingly terse too. The problem is that it doesn&#8217;t compile. As far as I know there is no way for a template to &#8220;return&#8221; a variable list of elements. In my opinion, this is a major language design flaw, but that&#8217;s just me. </p>
<p>There are several workarounds, none of them too exciting. One is to define a separate entity called a <var>typelist</var> along the lines of:</p>
<pre>template struct
<span style="color:#00f;">typelist&#60;hd, tl...&#62;</span> {
    typedef hd head;
    typedef typelist&#60;tl...&#62; tail;
};</pre>
<p>(As a matter of fact I have implemented typelists and related algorithms both in C++ and D.)</p>
<p>Another approach is to use continuations. Template parameter packs cannot be returned, but they can be passed to variadic templates (after expansion). So how about defining an algorithm like <var>map</var> to take one additional function that would consume the list that is the result of mapping? Such a function is often called a continuation, since it continues the calculation where normally one would return the result. First, let&#8217;s do it in Haskell:</p>
<pre>map_cont cont f lst = cont [f x &#124; x &#60;- lst]</pre>
<p>The function <var>map_cont</var> is just like <var>map</var> except that it takes a continuation, <var>cont</var>, and applies it to the result of mapping. We can test it by defining yet another implementation of <var>count</var>:</p>
<pre>count_cont lst = map_cont sum one lst</pre>
<p>The continuation here is the function <var>sum</var> that will be applied to the list produced by acting with function <var>one</var> on the list <var>lst</var>. Since this is quite a handful, let me rewrite it in a more familiar notation of runtime C++:</p>
<pre>int map_cont(int (*cont)(list), int (*f)(int), list lst) {
    list tmp;
    for (auto it = lst.begin(); it != lst.end(); ++it)
        tmp.push_front(f(*it));
    return cont(tmp);
}</pre>
<p>Now for the same thing in compile-time C++:</p>
<pre>template&#60;template&#60;class...&#62; class cont,
         template&#60;class&#62; class f,
         class... lst&#62; struct
<span style="color:#00f;">map_cont</span> {
    static const int value =
        cont&#60;typename f&#60;lst&#62;::type ...&#62;::value;
};</pre>
<p>It&#8217;s a one-to-one mapping of Haskell code&#8211;and it has very little in common with the iterative runtime C++ implementation. Also notice how loose the typing is in the TMP version as compared with the runtime version. The continuation is declared as a variadic template taking types, function <var>f</var> is declared as taking a type, and the list is a variadic list of types. Nothing is said about return types, except for the constraints that <var>f</var> returns a type (because <var>cont</var> consumes a list of types) and <var>cont</var> returns an <var>int</var>. Actually, this last constraint can be relaxed if we turn integers into types&#8211;a standard trick (hack?) in TMP:</p>
<pre>template&#60;int n&#62; struct
<span style="color:#00f;">Int</span> {
    static const int value = n;
};</pre>
<p>Loose typing&#8211;or &#8220;kinding,&#8221; as it is called for types of types&#8211;is an essential part of compile-time programming. In fact the popularity of the above trick shows that C++ kinding might be already too strong.</p>
<h2>The D Digression</h2>
<p>I&#8217;m grateful to Andrei Alexandrescu for reviewing this post. Since he objected to the sentence, &#8220;I&#8217;m disappointed that the D programming language followed the same path as C++ rather than lead the way,&#8221; I feel compelled to support my view with at least one example.  Consider various implementations of <var>all</var>. </p>
<p>In Haskell, beside the terse and elegant version I showed before:</p>
<pre>all pred [] = True
all pred (head:tail) = (pred head) &#38;&#38; (all pred tail)</pre>
<p>there is also a slightly more verbose one:</p>
<pre>all pred list =
    if null list then True
    else pred (head list) &#38;&#38; all pred (tail list)</pre>
<p>which translates better into D. The D version (taken from its standard library, Phobos) is not as short as Haskell&#8217;s, but follows the same functional paradigm:</p>
<pre>template allSatisfy(alias F, T...) {
    static if (T.length == 1)
    {
        alias F!(T[0]) <span style="color:#00f;">allSatisfy</span>;
    }
    else
    {
        enum bool <span style="color:#00f;">allSatisfy</span> = F!(T[0]) &#38;&#38; allSatisfy!(F, T[1 .. $]);
    }
}</pre>
<p>It definitely beats C++, there&#8217;s no doubt about it. There are some oddities about it though. Notice that the type tuple, <var>T&#8230;</var> gets the standard list treatment, but the split into the head and tail follows the array/slice notation. The head is <var>T[0]</var> and the tail is an array slice, <var>T[1..$]</var>. Instead of using <var>value</var> for the return value, D uses the &#8220;eponymous hack,&#8221; as I call it. The template &#8220;returns&#8221; the value using its own name. It&#8217;s a hack because it breaks down if you want to define the equivalent of &#8220;local variable&#8221; inside a template. For instance, the following code doesn&#8217;t compile:</p>
<pre>template allSatisfy(alias F, T...) {
    static if (T.length == 1)
    {
        alias F!(T[0]) allSatisfy;
    }
    else
    {
        <span style="color:#00f;">private enum bool tailResult = allSatisfy!(F, T[1..$]);</span>
        enum bool allSatisfy = F!(T[0]) &#38;&#38; tailResult;
    }
}</pre>
<p>This breaks one of the fundamental property of any language: decomposability. You want to be able to decompose your calculation into smaller chunks and then combine them together. Of course, you may still use decomposition if you don&#8217;t use the eponymous hack and just call your return value <var>value</var>. But that means modifying all the calling sites. </p>
<p>By the way, this is how decomposition works in Haskell:</p>
<pre>all2 pred [] = True;
all2 pred (head:tail) = (pred head) &#38;&#38; tailResult
    where tailResult = all2 pred tail</pre>
<p>Anyway, the important point is that there is <i>no reason</i> to force functional programming paradigm at compile-time. The following hypothetical syntax would be much easier for programmers who are used to imperative programming:</p>
<pre>template allSatisfy(alias Pred, T...) {
    foreach(t; T)
        if (!Pred!(t))
            return false;
    return true;
}</pre>
<p>In fact it&#8217;s much closer to the parameterized runtime function proposed by Andrei:</p>
<pre>bool all(alias pred, Range)(Range r) {
    foreach (e; r)
        if (!pred(e))
            return false;
    return true;
}</pre>
<p>This is why I&#8217;m disappointed that the D programming language followed the same path as C++ rather than lead the way.</p>
<h2>Conclusions</h2>
<p>I have argued that some familiarity with Haskell may be really helpful in understanding and designing templates in C++. You might ask why C++ chose such horrible syntax to do compile-time functional programming. Well, it didn&#8217;t. The ability to do compile-time calculations in C++ was <i>discovered</i> rather than built into the language. It was a very fruitful discovery, as the subsequent developments, especially the implementation of the Boost MPL, have shown. However, once the functional paradigm and its weird syntax took root in C++ TMP, it stayed there forever. I&#8217;m aware of only one effort to rationalize C++ TMP by Daveed Vandevoorde in <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1471.pdf">Reflective Metaprogramming in C++</a>. </p>
<p>I have tested all code in this blog using the Hugs interpreter for Haskell and the GNU C++ compiler v. 4.4.1 with the special switch <var>-std=c++0x</var>. The names I used in the blog might conflict with the standard definitions. For instance, Hugs defines its own <var>map</var> and <var>foldr</var>.</p>
<p>If you want to learn more about template metaprogramming, I recommend two books:</p>
<ol>
<li>Andrei Alexandrescu, Modern C++ Design</li>
<li>David Abrahams and Aleksey Gurtvoy, C++ Template Metaprogramming</li>
</ol>
<p>The reference I used for variadic templates was the paper by <a href="http://www.osl.iu.edu/~dgregor/cpp/variadic-templates.pdf">Douglas Gregor, Jaakko J&#228;rvi, and Gary Powell</a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[A JavaScript War Story]]></title>
<link>http://invisibleblocks.wordpress.com/2009/10/20/a-javascript-war-story/</link>
<pubDate>Wed, 21 Oct 2009 02:03:46 +0000</pubDate>
<dc:creator>Daniel Bernier</dc:creator>
<guid>http://invisibleblocks.wordpress.com/2009/10/20/a-javascript-war-story/</guid>
<description><![CDATA[What follows is an account from the author&#8217;s experience. Some details have been changed for th]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><i>What follows is an account from the author&#8217;s experience.  Some details have been changed for the usual reasons, and a poor memory has fuzzed out the rest.</i></p>
<p><i><b>UPDATE:</b> it <a href="http://www.reddit.com/r/javascript/comments/9w53i/a_javascript_war_story/c0eqxrd">turns out</a> the technique described below is known as <a href="http://en.wikipedia.org/wiki/Switch#Contact_bounce">debouncing</a>.  What an awesome name!</i></p>
<p>My last job was for a company that made case-management software.  With this software, you could track all kinds of data about your case: you could categorize it, sub-categorize it, say where and when it happened, note whether it was still open, track who was responsible&#8230;all kinds of stuff, great for data fiends.</p>
<p>One of our customers&#8217; favorite features was the reports, and they were pretty spiffin&#8217;.  But, not being ones to rest on our laurels, we were adding pivot-table reports, so you could count the number of cases, grouped by any criteria you wanted.  The input screen let the customer pick their pivot criterion, and which criteria they wanted as columns, for sub-counts.  We struggled to name these UI fields &#8212; something lucid, something explanatory, something <i>evocative</i> &#8212; something to make them understand what kind of report they were in for.  After a while, we decided to just <i>show</i> them: when they changed their pivot criterion, we&#8217;d run some javascript to render a skeleton report, same as the real report, but minus the data.  It would save them time, and save our servers.</p>
<p>The javascript was pretty involved.  It had to generate the same HTML as we did for the pivot table, which meant it had to know (or make up) values for each criterion, like all the case categories and sub-categories, and which sub-categories belonged to which categories.  And we let the customers pivot on up to THREE, count &#8216;em, different criteria.  And it had to happen each time the user picked different pivot criteria.  It took a few tricks, but we got it working.  It ran slowly, maybe a few seconds, but it was quick enough, probably, especially once we threw in a little &#8220;please wait&#8221; spinner.  Then we realized we needed to re-render whenever the window resized.</p>
<p>No biggie, I thought, and I quickly added <code>window.onResize(reportPreview);</code>.  It worked great, except it re-rendered the report with every pixel-wide movement of the mouse, as the window was dragged to new widths and heights.  Calling a function, one that runs for a few seconds, <i>a hundred times</i> in the time it took to widen the browser an inch, meant a locked browser.  It meant &#8220;time to get more coffee,&#8221; and after, &#8220;time to fix the bug.&#8221;</p>
<p>I knew we could delay calling <code>reportPreview</code>, but we only wanted to delay it when the window was being resized &#8212; when the user changed the columns, there was no reason to wait.  I was sure <code>window.setTimeout()</code> would do what we needed, but I didn&#8217;t want to muck up <code>reportPreview()</code> with it.</p>
<p>I&#8217;d been reading <a href="http://www.amazon.com/gp/product/0262560992?ie=UTF8&#38;tag=invisblock-20&#38;linkCode=as2&#38;camp=1789&#38;creative=390957&#38;creativeASIN=0262560992">The Little Schemer</a> lately, and noticing some striking similarities between javascript and scheme: first-class functions, and higher-order functions that take functions as arguments, and return other functions as values.  It was fun reading, with its strange teacher-student dialog style.  The material was better than brainteasers, and I knew it would make me a better programmer down the road, but I didn&#8217;t think of it as relevant to the day-job, as&#8230;applicable.</p>
<p>Then I realized higher-order functions were a way out of this.  I could write a function, <code>delay</code>, that would wrap one long-running, slow-poke function in <i>another</i> function: an intermediary that you could call as many times a second as you wanted, but it would only call the slow-poke once things had settled down.  <code>delay</code> would let us keep <code>setTimeout</code> out of <code>reportPreview</code>.  Something like this:</p>
<pre class="brush: jscript;">
function delay(millis, slowPoke) {
    var timeoutId = undefined;

    // This is the intermediary.  Call it lots, it won't hurt.
    return function() {
        if (timeoutId) {  // If we're waiting...
            clearTimeout(timeoutId); // re-start the clock.
        }
        timeoutId = window.setTimeout(slowPoke, millis);
    }
}
</pre>
<p>The first time you call the intermediary, it tells the window to call <code>slowPoke</code> after a bit, but every time you call it after that, it starts the clock over.  It&#8217;s like when you&#8217;re in a five-minute time-out, and you start acting up after only three, so your mom says &#8220;Ok, buster, another five minutes.&#8221;</p>
<pre class="brush: jscript;">
var fiveMinutes = 5 * 60 * 1000;
var screamAndShout = delay(fiveMinutes, function() {
    getBackToPlaying();
});

screamAndShout(); // Aw nuts, I'm in time-out.

// I'll be good for as long as I can, but...
screamAndShout(); // dang, five MORE minutes!
</pre>
<p>Once <code>delay</code> was in place, running <code>reportPreview</code> when the window was resized was no problem.</p>
<pre class="brush: jscript;">
function reportPreview() {
    // recursion, DOM manipulation, insanity...
}
columnPicker.onChange(reportPreview);
window.onResize(delay(100, reportPreview));
</pre>
<p>After testing, we found that delaying it for 100 milliseconds made all the difference in the world.</p>
<p><i>Do you have a war story?  Share it, and start the healing: tell a short one in the comments, or link to a longer one on your own damn blog.</i>   </p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Explore Clojure: Building a Bifid cipher]]></title>
<link>http://reminiscential.wordpress.com/2009/10/20/explore-clojure-building-a-bifid-cipher/</link>
<pubDate>Tue, 20 Oct 2009 17:28:09 +0000</pubDate>
<dc:creator>jchiu1106</dc:creator>
<guid>http://reminiscential.wordpress.com/2009/10/20/explore-clojure-building-a-bifid-cipher/</guid>
<description><![CDATA[Lately I&#8217;ve been teaching myself Clojure, a Lisp dialect on the JVM platform. I still love Erl]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Lately I&#8217;ve been teaching myself <a href="http://clojure.org">Clojure</a>, a Lisp dialect on the JVM platform. I still love Erlang and still learning it, but Clojure has a special draw for me being a JVM language and its Lisp roots. I studied Scheme (another Lisp dialect) in my college years and deemed it purely academic. However, Clojure has the potential of changing this and bring the expressiveness of Lisp and the power of functional programming to the Java world.</p>
<p>The best way to learn a language is to use it to solve some non-trivial practical problems. I stumbled <a href="http://programmingpraxis.com/2009/10/13/bifid-cipher/">this</a> problem on <a href="http://programmingpraxis.com">Programming Praxis</a>. It&#8217;s about building a <a href="http://en.wikipedia.org/wiki/Bifid_cipher">Bifid cipher</a>, which I thought could be a good practical problem for me to solve in Clojure.</p>
<h1>Polybius Square</h1>
<p>Bifid cipher is based on <a href="http://en.wikipedia.org/wiki/Polybius_square">Polybius Square</a>, which looks like this:</p>
<p>1 2 3 4 5<br />
1 B G W K Z<br />
2 Q P N D S<br />
3 I O A X E<br />
4 F C L U M<br />
5 T H Y V R</p>
<p>Every encodable letter is given a vector value, which is the coordinate in this square. For example, X=[3 4], H=[5 2]. The first task would be building the Polybius square in Clojure.</p>
<p>My function <code>polybius-square</code> is going to take 2 parameters: <code>charset</code> is a list of encodable characters, and <code>size</code> is the size of the Polybius square.</p>
<pre class="brush: css;">
(defn polybius-square
  &#34;Polybius square by the given charset and size&#34;
  [charset square-size]
  (map #(vector %1 [%2 %3]) charset
    (for [x (range 1 (+ 1 square-size)), y (range 1 (+ 1 square-size))] x)
    (take (* square-size square-size) (cycle (range 1 (+ 1 square-size))))))
</pre>
<p>Let&#8217;s see how this works. Suppose you&#8217;re calling this function with<br />
<code>(polybius-square "ABCDE" 3)</code>, <code>charset</code> is bound to &#8220;ABCDE&#8221; and <code>size</code> is bound to 3. What I want is a seq of vectors in the form of: <code>(\Letter [x y])</code> where x and y are the coordinates. It&#8217;s natural to use map, with the function-to-map taking three parameters and vectorize them. That&#8217;s what the anonymous function does:<br />
<code>#(vector %1 [%2 %3])</code></p>
<p>%1 is the letter, %2 and %3 are the coordinates. I want the coordinate sequence to be like this: [1 1], [1 2], [1 3], [2 1], [2 2], [2 3]. In imperative language, you&#8217;d use a nested for loop, but we&#8217;ve established that&#8217;s ugly. We want the parameters fed to <code>map</code> to be of the following:<br />
<code>"ABCDEFGHJI" (1 1 1 2 2 2 3 3 3) (1 2 3 1 2 3 1 2 3 1 2 3)</code></p>
<p>To generate the first list, we use list comprehension:<br />
<code>(for [ x (range 1 (+ 1 square-size)), y (range 1 (+ 1 square-size))] x)</code><br />
It reads: for every <code>x</code> in range 1 to square-size+1 (because &#8220;range&#8221; is right-exclusive) and for every <code>y</code> in the same range, output the value of x and take the whole output as the list. Because the binding of y comes later, and Lisp evaluates from right to left, the result of this list comprehension is (1 1 1 2 2 2 3 3 3)</p>
<p>Now let&#8217;s look at the other list: (1 2 3 1 2 3 1 2 3) &#8211; a cyclic list. Fortunately, Clojure has a built-in cycle function, which returns a lazy sequence of cycles of a collection. We want to call it with <code>cycle '(1 2 3)</code>, so it&#8217;s going to be <code>cycle (range 1 (+ 1 square-size))</code>. Because cycle will be evaluated to an infinite sequence, we have to tell it when to stop.<br />
When you see the square as a flat list, it&#8217;s clear that the cycle should stop when it reaches square-size^2, hence <code>(take (* square-size square-size) (cycle (range 1 (+ 1 square-size))))</code>.</p>
<h1>The codec maps</h1>
<p>After the Polybius square is built, we have the bases for our encryption. However, it&#8217;s not user-friendly: it&#8217;s a flat list of tuples. We want two maps for fast searching from letters to their encoding forms (<code>letter-2-code</code>) and from transposed vectors to the letters (<code>transposed-2-letter</code>).</p>
<pre class="brush: css;">
(defn- letter-2-code
  &#34;Produce a mapping between letters and their codes&#34;
  [square]
  (letfn [(helper [the-square the-map]
          (if (empty? the-square)
            the-map
            (let [the-item (first the-square)
                  the-key (first the-item)
                  the-number (second the-item)]
              (recur (rest the-square) (assoc the-map the-key the-number)))))]
    (helper square (empty hash-map))))
</pre>
<p>The strategy here is to walk through the list, add each item to a <code>hash-map</code>. Here we define an inner function, which is basically a recursive helper. The function itself is pretty straightforward. Take note that in Clojure, when you need to do tail recursion, always use <code>recur</code> instead of calling the function by its name. This is because JVM cannot do automatic tail cut optimization (TCO), but Clojure does the optimization through the <code>recur</code> keyword. After the binding, we kick off the recursion by calling it with the initial list.</p>
<p>In the similar fashion, we have:</p>
<pre class="brush: css;">
(defn- transposed-2-letter
  &#34;Produce a mapping between the transposed codes to letter&#34;
  [square]
  (letfn [(helper [the-square the-map]
            (if (empty? the-square)
              the-map
              (let [the-item (first the-square)
                    the-key (second the-item)
                    the-letter (first the-item)]
                (recur (rest the-square) (assoc the-map the-key the-letter)))))]
    (helper square (empty hash-map))))
</pre>
<h1>Encode</h1>
<p>Now comes the encode function. It&#8217;s important to note that the encoding will be different if a different polybius square is provided. Therefore, both <code>encode</code> and <code>decode</code> functions take the Polybius square as parameter.</p>
<p>During the encoding phase, we first convert every character in the message into a vector, then reorganize the vectors. To better illustrate, we use an example:<br />
Suppose we have the following mapping:<br />
<code>{I [3 3], H [3 2], G [3 1], F [2 3], E [2 2], D [2 1], C [1 3], B [1 2], A [1 1]}</code><br />
and we want to encode the word &#8220;CEDE&#8221;<br />
CEDE =&#62; ([1 3] [2 2] [2 1] [2 2]), then we want to transpose the &#8220;matrix&#8221; composed of the above vectors, so it would be like:<br />
([1 2] [2 2] [3 2] [1 2]), and finally looking up every item in the transposed-2-letter mapping<br />
<code>{[3 3] I, [3 2] H, [3 1] G, [2 3] F, [2 2] E, [2 1] D, [1 3] C, [1 2] B, [1 1] A}</code><br />
=&#62;BEHB</p>
<p>To get a mapping of message to vectors, we again map a function to the list:<br />
<code>(map #(get l2c % %) message)</code> (l2c has been bound)<br />
Then we apply the interleave function to the result, this gives:<br />
<code>(1 2 2 2 3 2 1 2)</code>. This is good but we want a list of vectors instead of a flat list. Clojure provides <code>partition</code> function, which does exactly it:<br />
<code>(partition 2 '(1 2 2 2 3 2 1 2))</code><br />
gives:<br />
<code>([1 2] [2 2] [3 2] [1 2])</code></p>
<p>Then, we want to lookup every item in the result in the transposed-to-letter map and get a list of mapped characters. To achieve this, again, we use <code>map</code>, providing a different mapping:<br />
<code>(map #(get tr2l % %) ...)</code> (tr2l is bound)<br />
This returns a list of characters. We want a string, so we concatenate the characters by applying <code>str</code> function:<br />
<code>(apply str (map #(get tr2l % %) ...))</code></p>
<p>Here&#8217;s the complete code:</p>
<pre class="brush: css;">
(defn encode
  &#34;Return the message encoded by the specified polybius-square&#34;
  [message polybius-square]
  (let [l2c (letter-2-code polybius-square)
        tr2l (transposed-2-letter polybius-square)]
    (apply str
      (map #(get tr2l % %) (partition 2 (apply interleave (map #(get l2c % %) message)))))))
</pre>
<p>Here you see the expressiveness of Clojure: all operations are chained together and formed in expression.</p>
<p>The <code>decode</code> function behaves similarly. The only trick is we need to split the translated code list in two. We use <code>partition</code> method again, with <code>size</code> being half of the entire list.</p>
<pre class="brush: css;">
(defn decode
  &#34;Return the decoded message using the specified polybius-square&#34;
  [encoded polybius-square]
  (let [l2c (letter-2-code polybius-square)
        c2l (transposed-2-letter polybius-square)
        codes (apply concat (map #(get l2c % %) encoded))
        len (count codes)
        parts (partition (/ len 2) codes)]
    (apply str (map #(get c2l %1 %1) (map #(vector %1 %2) (first parts) (second parts))))))
</pre>
<h1>Putting it together</h1>
<p>Now with all the pieces are in place, we can put it together by writing a simple test:</p>
<pre class="brush: css;">
(defn -main
  &#34;A simple test case entry point&#34;
  []
  (let [square (polybius-square &#34;ABCDEFGHIKLMNOPQRSTUVWXYZ&#34; 5)]
    (do (println (encode &#34;BIFIDCIPHER&#34; square))
      (println (decode (encode &#34;BIFIDCIPHER&#34; square) square)))))
</pre>
<p>Output:<br />
<code><br />
BGAHFRQTOXW<br />
BIFIDCIPHER<br />
</code></p>
<p>Have the complete source code here at <a href="http://github.com/kevinjqiu/bifid-clj">http://github.com/kevinjqiu/bifid-clj</a>, I&#8217;m sure there are a lot to be improved of the above implementation of the Bifid cipher. Especially currently I have no elegant way to solve the situation where the letter to be encoded is not in the Polybius square. Also, I&#8217;m sure my code isn&#8217;t entirely the idiomatic Clojure. If you have any suggestions, don&#8217;t hesitate to write a comment.</p>
<p>Although I have been learning Clojure for 3 days, I&#8217;m already enjoying its expressiveness and the clean look. As a Java programmer, Clojure also gives me the benefit of full access to the Java land. The potential is endless!</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[IASRA is a stupid recursive acronym!]]></title>
<link>http://saschpe.wordpress.com/2009/10/19/iasra-is-a-stupid-recursive-acronym/</link>
<pubDate>Mon, 19 Oct 2009 13:06:21 +0000</pubDate>
<dc:creator>Sascha Peilicke</dc:creator>
<guid>http://saschpe.wordpress.com/2009/10/19/iasra-is-a-stupid-recursive-acronym/</guid>
<description><![CDATA[To recurse or not to recurse? This is of course a brilliant idea if you&#8217;re in search for a coo]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>To recurse or not to recurse? This is of course a brilliant idea if you&#8217;re in search for a cool and geeky name for your new pet project. But is it also wise to code your-favorite-algorithm &#8482; in a recursive manner?</p>
<p>Let&#8217;s start with the basics, Wikipedia has a <a href="http://en.wikipedia.org/wiki/Recursion">good definition</a> available:</p>
<blockquote><p>
Recursion, in mathematics and computer science, is a method of defining functions in which the function being defined is applied within its own definition.
</p></blockquote>
<p>Furthermore, in our first Computer Science semester we where taught the logical equivalence of coding an algorithm in an applicative or imperative way. So what&#8217;s the matter then? As usual, problems arise when reality hits (Computer Science) theory hard. Generally spoken, those two methods of encoding an algorithm differ physically. Ok, what&#8217;s meant by that? Well, depending on the used language (more to that soon), it is wise to use the former or the latter way. Let&#8217;s start out with good old procedural languages like C, C++, Java and all the others that actually matter. Procedural languages use functions to encapsulate sub-problems. For example, when a C++ program is transformed into machine-specific assembly, the compiler enforces certain conventions that ensure that these functions can be called in an uniform way. Executing a function usually means to jump to a different portion of code, do something and to jump back to where you&#8217;ve been before to  use the computed result. So we have to store that return address. The function concept becomes more powerful if you can send parameters to them, so we have to store those too. Functions tend to use local variables for saving intermediate result and every function call needs a local copy of those variables, so these have to be stored somewhere too. The convention on how to store all this is usually referred to as a <a href="http://en.wikipedia.org/wiki/Stack_frame#Structure">stack frame</a>. As the name implies, a certain <em>frame</em> is stored on the stack, a certain memory area that was set up by your kind operating system for your proggy&#8217;s process in advance. Let&#8217;s shamelessly steal a picture from Wikipedia to visualize this concept:</p>
<p><img src="http://upload.wikimedia.org/wikipedia/commons/e/e7/Call_stack_layout.png" alt="Stack frame example" /></p>
<p>Note that the actual frame layout differs with the language that you use. For example Pascal-derived languages use a different layout than the C world. It easy to see that this unavoidable <em>overhead</em> gets bigger (relative, not absolute) the shorter your functions are. Recursive algorithms generally tend to use short functions, which is shown exemplarily with this C++ implementation of the <a href="http://en.wikipedia.org/wiki/Fibonacci_number">Fibonacci numbers</a>:</p>
<p><code><br />
int fib(unsigned int n)<br />
{<br />
    if (n == 0) {<br />
        return 0;<br />
    } else if (n == 1) {<br />
        return 1;<br />
    } else {<br />
        return fib(n - 1) + fib(n -2);<br />
    }<br />
}<br />
</code></p>
<p>This means big relative overhead. Let&#8217;s look at the imperative (and optimised) version of the same algorithm:</p>
<p><code><br />
int fib(unsigned int n)<br />
{<br />
    static unsigned int tmp[] = {0, 1};<br />
    static std::vector fibs(tmp, tmp + sizeof(tmp) / sizeof(unsigned int));</p>
<p>    if (n &#62;= fibs.size()) {<br />
        for (unsigned int i = fibs.size() - 1; i &#60; n; i++) {<br />
            fibs.push_back(fibs[i] + fibs[i - 1]);<br />
        }<br />
    }<br />
    return fibs[n];<br />
}<br />
</code></p>
<p>One function means one stack frame, easy peasy. So to say, the overall runtime and memory cost of those stack frames increases the more excessive you execute short functions from within functions (hey, that&#8217;s recursion!). The imperative version only uses one stack frame, which saves us countless bytes on the stack (speak, main memory) and reduces the risk of stack overflows. Furthermore it saves CPU cycles for those push/pop and store/fetch instructions you don&#8217;t have to execute (The <a href="http://en.wikipedia.org/wiki/Inline_function">inline</a> keyword in C/C++ comes to mind here). Therefore it is always faster to go imperative than recursive in the real world. This concludes to:</p>
<p><strong>NEVER EVER USE RECURSION IN A PROCEDURAL LANGUAGE !</strong></p>
<p>However, the situation looks slightly different if you use a functional language (or even handcraft the Fibonacci algorithm in assembly, but that&#8217;s another story). Functional languages often use the <a href="http://en.wikipedia.org/wiki/Tail_recursion">tail recursion</a> idiom to allow (or force, depending on personal opinion) the user to encode algorithms recursively. What happens when that get&#8217;s translated into assembly? That idiom is simply mappend back to simple loops for the exact same reason (remember, they&#8217;re equivalent logically). This post already got longer than I expected, so let&#8217;s keep it short. Functional languages allow convenience recursion idioms that get translated back to imperative idioms to run performant on real hardware. Maybe someone more experienced in Haskell can provide more detail how this is done exactly (assembly listings appreciated). </p>
<p>If you want to confirm the above, take the attached little test programs and run them through your favorite profiler and compare jump/call counts and stack changes. You might want to check what time one iteration of the algorithm takes (speak one loop iteration versus one recursive function call). That&#8217;s it!</p>
<ul>
<li><a href="http://pastebin.com/d7174265e">fib_imperative.cpp</a></li>
<li><a href="http://pastebin.com/f6457dc98">fib_recursive.cpp</a></li>
</ul>
</div>]]></content:encoded>
</item>

</channel>
</rss>
