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

<channel>
	<title>Desk Checked &#187; Functional Programming</title>
	<atom:link href="http://www.deskchecked.com/category/functional-programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.deskchecked.com</link>
	<description>Thomas Lee's programming blog</description>
	<lastBuildDate>Sun, 29 Nov 2009 13:01:58 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Clojure and MessageDigest</title>
		<link>http://www.deskchecked.com/2009/06/22/clojure-and-messagedigest/</link>
		<comments>http://www.deskchecked.com/2009/06/22/clojure-and-messagedigest/#comments</comments>
		<pubDate>Mon, 22 Jun 2009 09:58:28 +0000</pubDate>
		<dc:creator>tom</dc:creator>
				<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://www.deskchecked.com/?p=209</guid>
		<description><![CDATA[Last night I needed a quick and dirty SHA function for a clojure-based web application. MessageDigest to the rescue!

(ns com.deskchecked.utils
  (:use clojure.contrib.str-utils)
  (:import [java.security MessageDigest]))

(defn sha
  "Generates a SHA-256 hash of the given input plaintext."
  [input]
  (let [md (MessageDigest/getInstance "SHA-256")]
    (. md update (.getBytes input))
   [...]]]></description>
			<content:encoded><![CDATA[<p>Last night I needed a quick and dirty SHA function for a clojure-based web application. MessageDigest to the rescue!</p>
<pre><code>
(ns com.deskchecked.utils
  (:use clojure.contrib.str-utils)
  (:import [java.security MessageDigest]))

(defn sha
  "Generates a SHA-256 hash of the given input plaintext."
  [input]
  (let [md (MessageDigest/getInstance "SHA-256")]
    (. md update (.getBytes input))
    (let [digest (.digest md)]
      (str-join "" (map #(Integer/toHexString (bit-and % 0xff)) digest)))))
</code></pre>
<p>There&#8217;s obviously a dependency on clojure-contrib here which you can do away with if you don&#8217;t need it. And of course, you can pick a hashing algorithm to suit your needs. </p>
<p>Nothing exciting, but I figure I can&#8217;t be the only person in need of this sort of stuff. <img src='http://www.deskchecked.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.deskchecked.com/2009/06/22/clojure-and-messagedigest/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JVM Compiler Construction with Scala and BCEL, Part 1.5</title>
		<link>http://www.deskchecked.com/2008/07/09/jvm-compiler-construction-with-scala-and-bcel-part-15/</link>
		<comments>http://www.deskchecked.com/2008/07/09/jvm-compiler-construction-with-scala-and-bcel-part-15/#comments</comments>
		<pubDate>Wed, 09 Jul 2008 11:16:04 +0000</pubDate>
		<dc:creator>tom</dc:creator>
				<category><![CDATA[Compiler Construction with Scala and BCEL]]></category>
		<category><![CDATA[Compilers]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Scala]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://www.vector-seven.com/?p=73</guid>
		<description><![CDATA[The second part of my Scala compiler construction tutorial has been a long time coming. This post is, unfortunately, not the second part of the article &#8212; although that is coming soon. Honest.
Since part 1 was published, Scala 2.7 has been released which &#8212; among other things &#8212; introduced changes to the parser combinator library. [...]]]></description>
			<content:encoded><![CDATA[<p>The second part of my Scala compiler construction tutorial has been a long time coming. This post is, unfortunately, <em>not</em> the second part of the article &#8212; although that is coming soon. Honest.</p>
<p>Since <a href="http://www.deskchecked.com/2007/11/03/jvm-compiler-construction-with-scala-and-bcel-part-1/">part 1</a> was published, Scala 2.7 has been released which &#8212; among other things &#8212; introduced changes to the parser combinator library. Changes that meant the source code from part 1 <em>will not compile</em> in Scala 2.7. Sorry about that. Updated, working code can be found at the end of this post.</p>
<p>So what exactly has changed? Well, let&#8217;s see &#8230;</p>
<p><strong>keyword() no longer discards its result</strong></p>
<p>A bit of a refresher first:</p>
<p>In both Scala 2.6 and 2.7, the keyword implicit is called whenever you use a string in your &#8220;grammar rules&#8221;. For example:</p>
<pre><code>def sum = expr ~ "+" ~ expr</code></pre>
<p>Is the equivalent of:</p>
<pre><code>def sum = expr.~(keyword("+").expr)</code></pre>
<p>In Scala 2.6&#8217;s parser combinator library, the result of the keyword() call was actually the UnitParser &#8212; that is, a parser that would discard its result. At the time, that meant we could use the tilde operator (&#8221;~&#8221;) to create a sequenced parser and everything was fine:</p>
<pre><code>def sum = expr ~ "+" ~ expr ^^
    ((left : Expr, right : Expr) => Sum(left, right))</code></pre>
<p>In 2.7, the keyword() implicit returns a Parser[String] rather than a UnitParser. This means we have to either deal with the newly introduced tokens as follows:</p>
<pre><code>def sum = expr ~ "+" ~ expr ^^
    ((left : Expr, op : String, right : Expr) => Sum(left, right))</code></pre>
<p>Or alternatively &#8230;</p>
<p><strong>Use <~ and ~> to indicate the important parts of a parse rule</strong></p>
<p>Let&#8217;s start with something simple based on the 2.6 combinators:</p>
<pre><code>def bracketExpr = "(" ~ expr ~ ")" ^^ ((e : Expr) => e)</code></pre>
<p>Again, in 2.7 we know that keyword() is no longer a UnitParser, so we have to deal with it like so:</p>
<pre><code>def bracketExpr = "(" ~ expr ~ ")" ^^
    ((l : String, e : Expr, r : String) => e)</code></pre>
<p>Alright, this compiles and does what we expect. But why should we keep those strings around if we don&#8217;t need them? They sure do clutter up the code a whole bunch.</p>
<p><~ and ~> can be used to include or discard the result of a given parser. <~ builds a parser that takes the result of two parsers (the parsers to its left and right) and builds a parser that takes the result of both and discards the result of the one on the right. Conversely, ~> yields a parser that takes the result of both parsers and discards the result on the left.</p>
<p>So, using these two operators we can rewrite bracketExpr as follows:</p>
<pre><code>def bracketExpr = "(" ~> expr <~ ")" ^^
    ((e : Expr) => e)</code></pre>
<p>Ah. Much better. <img src='http://www.deskchecked.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>The ^^^ operator</strong></p>
<p>I had to go digging in the Scala source code to work out what exactly this one does.</p>
<p>First, let&#8217;s take a look at some 2.6 code:</p>
<pre><code>def simpleExpr = term * (
    "+" ^^ ((x : Expr, y : Expr) => Add(x, y)) |
    "-" ^^ ((x : Expr, y : Expr) => Sub(x, y))
)</code></pre>
<p>In 2.6, this can parse zero or more repetitions of &#8220;term&#8221; interleaved by &#8220;+&#8221; and &#8220;-&#8221; (check out part 1 if you need a refresher on how the * combinator works). In 2.7 it&#8217;s a compile-time error because of the fact keyword() is no longer a UnitParser (are you seeing a pattern here? <img src='http://www.deskchecked.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ), and ^^ is trying to pass the resulting String on to the anonymous method in each case.</p>
<p>If we use the ^^^ operator here, we can effectively discard the result of the keyword parse, and build a parser that uses a simple anonymous method to parse the current pair of terms:</p>
<pre><code>def simpleExpr = term * (
    "+" ^^^ ((x : Expr, y : Expr) => Add(x, y)) |
    "-" ^^^ ((x : Expr, y : Expr) => Sub(x, y))
)</code></pre>
<p>Exactly what we&#8217;re after. This compiles and behaves as expected.</p>
<p><strong>What else?</strong></p>
<p>There may be more changes to the parser combinator library which I haven&#8217;t covered here, but I&#8217;m not going to go looking for any more changes since the updated code seems to work just fine. This should be enough to at least understand the updated code for the compiler described in part 1 without needing to deal with any cryptic compiler errors.</p>
<p><strong>Finally, the new code!</strong></p>
<p>Special thanks to <a href="http://makeclean.wordpress.com/">Harshad</a> for sending through working code for 2.7 ages ago which I never got around to posting here. This code, along with the <a href="http://www.scala-lang.org/docu/files/api/index.html">Scala API docs</a>, was used to figure out just what had changed since 2.6. The code below is derived from some code he sent to me a few months back.</p>
<p>I&#8217;m really sorry this has been so long in the making. I&#8217;ll try to get around to writing the &#8220;real&#8221; part two of this article. In the meantime, here&#8217;s the <a href="http://www.deskchecked.com/wp-content/uploads/2008/07/scala-compiler-nojvm-2.zip">updated code</a>. Thanks! Please post or email any comments or questions.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.deskchecked.com/2008/07/09/jvm-compiler-construction-with-scala-and-bcel-part-15/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>The Many Humps of Ocaml, Part 2</title>
		<link>http://www.deskchecked.com/2007/10/03/the-many-humps-of-ocaml-part-2/</link>
		<comments>http://www.deskchecked.com/2007/10/03/the-many-humps-of-ocaml-part-2/#comments</comments>
		<pubDate>Wed, 03 Oct 2007 11:02:03 +0000</pubDate>
		<dc:creator>tom</dc:creator>
				<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Ocaml]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[TMHOO]]></category>

		<guid isPermaLink="false">http://www.vector-seven.com/2007/10/03/the-many-humps-of-ocaml-part-2/</guid>
		<description><![CDATA[Welcome to part two in my series of Ocaml tutorials! There was an overwhelming response to the first tutorial in the series and I have taken plenty of suggestions on board for this and future tutorials. In this instalment I&#8217;ll be introducing the list data type and the very useful List.iter function from the Ocaml [...]]]></description>
			<content:encoded><![CDATA[<p>Welcome to part two in my series of Ocaml tutorials! There was an overwhelming response to the first tutorial in the series and I have taken plenty of suggestions on board for this and future tutorials. In this instalment I&#8217;ll be introducing the <em>list</em> data type and the very useful <em>List.iter</em> function from the Ocaml standard library.</p>
<p><strong>An Introduction to List Initialization and List.iter</strong></p>
<p>Here&#8217;s the source code we&#8217;re going to be breaking down:</p>
<pre><code>let main () =
    let seq = ["a"; "b"; "c"] in
    List.iter print_endline seq ;;

let _ = main ()</code></pre>
<p>Looks scary, doesn&#8217;t it? It&#8217;s actually quite simple, but we&#8217;ll get to the source code in a moment. First, let&#8217;s see the program&#8217;s output. Save this file as tmhoo02.ml and run it like so:</p>
<pre><code>$ ocaml tmhoo02.ml</code></pre>
<p>You should see the following:</p>
<pre><code>a
b
c</code></pre>
<p>Now, let&#8217;s take a look at the interesting bits of the source code:</p>
<pre><code>let seq = ["a"; "b"; "c"] in</code></pre>
<p>As you (hopefully!) learned in <a href="http://www.deskchecked.com/2007/07/06/the-many-humps-of-ocaml-part-1/">part 1</a>, the <em>let</em> syntax binds the variable <em>seq</em> to some expression. The <em>in</em> keyword indicates that this binding is a named local expression whose value to be discarded when the function exits (think &#8220;local variable&#8221;). But what exactly does that expression mean?</p>
<pre><code>["a"; "b"; "c"]</code></pre>
<p>This is the most direct way to initialize a <em>list</em> in Ocaml. Each element in a <em>list</em> is separated by a semi-colon. This particular list has three elements: the strings &#8220;a&#8221;, &#8220;b&#8221; and &#8220;c&#8221;. As our list comprises of string elements, we can say that this is a <em>string list</em>. Note that unlike some dynamically typed languages (e.g. Python and Ruby), every Ocaml list element must be of the same type: you have a list of string elements or a list of integer elements, but you simply can&#8217;t mix the two. Honestly, it won&#8217;t compile.</p>
<pre><code>List.iter print_endline seq ;;</code></pre>
<p>Here we&#8217;re calling the <em>iter</em> function of the <em>List</em> module &#8211; a module which is bundled as part of the Ocaml standard library. This function takes two parameters: the first is another function that accepts a single parameter, the second is a list.</p>
<p>As you might suspect, <em>List.iter</em> iterates over the list, passing each element in the list to the function one by one. To word it another way, inside <em>List.iter</em> we&#8217;re calling <em>print_endline</em> for each element in our list to the equivalent of: print_endline &#8220;a&#8221;, print_endline &#8220;b&#8221;, print_endline &#8220;c&#8221;. This explains the output of our example program.</p>
<p>Finally:</p>
<pre><code>let _ = main ()</code></pre>
<p><em>main</em> is evaluated here and its return value (the &lt;em&gt;unit&lt;/em&gt; value) is ignored by the underscore wildcard. You&#8217;ll notice in part 1 I omitted everything up to the equals operator but, at the behest of others who know better, I&#8217;ve included it here in part two. I&#8217;m not going to say anything more about it, other than the fact that the underscore wildcard is a simple but powerful construct you&#8217;ll likely become very familiar with at a later date. If you&#8217;d prefer to use the syntax from part 1, that should work too (but don&#8217;t come crawling to me when other Ocaml programmers come down on you like a ton of bricks <img src='http://www.deskchecked.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ).</p>
<p><strong>Advanced Discussion of the Type System</strong></p>
<p>As a sneak preview into Ocaml&#8217;s type system, I can tell you that <em>List.iter</em> isn&#8217;t restricted to string lists. In fact, it can work with lists containing elements of any type. However, because each element of the list is passed to the function given to <em>List.iter</em> as the first parameter, that function must accept a parameter the same type as a single element in the list. Since print_endline accepts a string, we must use a string list. Or: since we&#8217;re passing in a string list as the second parameter to <em>List.iter</em>, the function passed as the first parameter must itself accept a string as its sole parameter.</p>
<p>Confused? Read that last paragraph again carefully. If you still don&#8217;t understand it, don&#8217;t worry too much: we&#8217;ll cover Ocaml&#8217;s type system more in the next few tutorials.</p>
<p><strong>Until Next Time &#8230;<br />
</strong></p>
<p>So that wraps up tutorial number two. I&#8217;ve already got parts three and four in the pipeline and I can tell you they introduce a fair bit of new material. Take your time trying to understand what was covered in this tutorial and post a comment or two if you have any suggestions, questions or improvements. <img src='http://www.deskchecked.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.deskchecked.com/2007/10/03/the-many-humps-of-ocaml-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>thumper: My Ugly Little Ocaml Web Server</title>
		<link>http://www.deskchecked.com/2007/07/17/thumper-my-ugly-little-ocaml-web-server/</link>
		<comments>http://www.deskchecked.com/2007/07/17/thumper-my-ugly-little-ocaml-web-server/#comments</comments>
		<pubDate>Tue, 17 Jul 2007 05:31:55 +0000</pubDate>
		<dc:creator>tom</dc:creator>
				<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Ocaml]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://www.vector-seven.com/2007/07/17/thumper-my-ugly-little-ocaml-web-server/</guid>
		<description><![CDATA[Spent the afternoon cobbling together a simple Ocaml web server and &#8211; to spite my normally reclusive attitude when it comes to personal projects &#8211; I thought I&#8217;d share the results. The interesting stuff is in thumper.ml. Refer to line 215 if you&#8217;re interested in implementing your own handlers for primitive resources.
I&#8217;m sure there&#8217;s room [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.deskchecked.com/wp-content/uploads/2007/07/thumper-trunktar.gz" title="Thumper v0.1"></a>Spent the afternoon cobbling together a simple Ocaml web server and &#8211; to spite my normally reclusive attitude when it comes to personal projects &#8211; I thought I&#8217;d share the results. The interesting stuff is in thumper.ml. Refer to line 215 if you&#8217;re interested in implementing your own handlers for primitive resources.</p>
<p>I&#8217;m sure there&#8217;s room for improvement, so I&#8217;ve uploaded a tarball of the <a href="http://bazaar-vcs.org/" title="Bazaar-VCS">bzr</a> repository. You can get it here:Â <a href="http://www.deskchecked.com/wp-content/uploads/2007/07/thumper-trunktar.gz" title="Thumper v0.1">Thumper v0.1</a>. Any suggestions/patches?</p>
<p><strong>Note: </strong>This is not the next part of my series of Ocaml tutorials. That&#8217;s likely to come after I&#8217;ve finished moving. <img src='http://www.deskchecked.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.deskchecked.com/2007/07/17/thumper-my-ugly-little-ocaml-web-server/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
