<?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>raek&#039;s blog</title>
	<atom:link href="http://blog.raek.se/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.raek.se</link>
	<description>The read eval blog loop</description>
	<lastBuildDate>Fri, 19 Oct 2012 19:54:52 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.4</generator>
		<item>
		<title>Haskell I/O in Five Minutes</title>
		<link>http://blog.raek.se/2012/10/19/haskell-io-in-five-minutes/</link>
		<comments>http://blog.raek.se/2012/10/19/haskell-io-in-five-minutes/#comments</comments>
		<pubDate>Fri, 19 Oct 2012 19:35:02 +0000</pubDate>
		<dc:creator>raek</dc:creator>
				<category><![CDATA[Haskell]]></category>

		<guid isPermaLink="false">http://blog.raek.se/?p=282</guid>
		<description><![CDATA[The way you do I/O in Haskell may be radically different from what newcomers are used to, but in fact it follows a few simple rules.]]></description>
			<content:encoded><![CDATA[<p>The way you do I/O in Haskell may be radically different from what newcomers are used to, but in fact it follows a few simple rules. Let me try to explain.</p>
<p>For example, you might expect a line of text to pop up in the terminal when you apply <tt>putStrLn</tt> to <tt>"Hello"</tt> somewhere in a program. Actually, nothing happens!<sup><a href="http://blog.raek.se/2012/10/19/haskell-io-in-five-minutes/#footnote_0_282" id="identifier_0_282" class="footnote-link footnote-identifier-link" title="This is not true at the top level of the GHCi command-line since it handles I/O actions specially compared to other values.">1</a></sup> Instead the expression evaluates to a value which represents the action of printing &#8220;Hello&#8221;. Evaluating the expression does not cause the action to be performed.</p>
<p>I/O actions, such as <tt>putStrLn "Hello"</tt>, are just ordinary values. This means that you can put them in variables, store them in lists, pass them to functions and so on. In other words, I/O actions are <em>first class</em> values.</p>
<p>If you don&#8217;t perform an action by evaluating it, then how do you go about doing it? The answer is simple: you let it be <tt>main</tt>:</p>
<blockquote>
<pre><tt>main :: IO ()
main = putStrLn "Hello"</tt></pre>
</blockquote>
<p>When you run the program the Haskell runtime takes the value of <tt>main</tt> (which must be an I/O action) and performs it. With only this &#8220;recipe for I/O&#8221; presented so far at hand, it seems like we can only perform one single action.</p>
<p>How do you perform two actions, then? It turns out that there is a way to combine two I/O actions into one action. To understand Haskell code I find it very useful to look at the types, so let&#8217;s first do that for two useful actions:</p>
<blockquote>
<pre><tt>putStrLn :: String -&gt; IO ()
getLine  :: IO String</tt></pre>
</blockquote>
<p>The first line should be read as &#8220;<tt>putStrLn</tt> is a function that takes a string and returns an action that, when performed, produces <tt>()</tt><sup><a href="http://blog.raek.se/2012/10/19/haskell-io-in-five-minutes/#footnote_1_282" id="identifier_1_282" class="footnote-link footnote-identifier-link" title="This is read as &amp;#8220;unit&amp;#8221; and means &amp;#8220;no useful value&amp;#8221;.">2</a></sup>&#8221;. The the second should be read as &#8220;<tt>getLine</tt> is an action that, when performed, produces a string&#8221;.</p>
<p>The function that combines two actions is called &#8220;bind&#8221; an is written in Haskell as the infix operator &#8220;<tt>&gt;&gt;=</tt>&#8220;. It has the following type:</p>
<blockquote>
<pre><tt>(&gt;&gt;=) :: IO a -&gt; (a -&gt; IO b) -&gt; IO b</tt></pre>
</blockquote>
<p>Bind takes two arguments (the left and right operands) and returns a compound action. The meaning of this new action is to first perform the action to the left. The left action produces a value of type <tt>a</tt>. Then the function to the right is applied with this value, which returns a second action. Finally the second action is performed. The value it produces becomes the result of the whole compound action.</p>
<p>With this new ingredient it is possible to define an action that does two things, for example reading and printing:</p>
<blockquote>
<pre><tt>main :: IO ()
main = getLine &gt;&gt;= (\line -&gt; putStrLn (reverse line))</tt></pre>
</blockquote>
<p>This example reads a line from the terminal, reverses it, and prints it back. Finally there is another function which come handy when you compose action. It is called &#8220;<tt>return</tt>&#8221; and has the following type<sup><a href="http://blog.raek.se/2012/10/19/haskell-io-in-five-minutes/#footnote_2_282" id="identifier_2_282" class="footnote-link footnote-identifier-link" title="In reality, the (&amp;gt;&amp;gt;=) and return functions do actually involve a more general type than IO.">3</a></sup>:</p>
<blockquote>
<pre><tt>return :: a -&gt; IO a</tt></pre>
</blockquote>
<p>That is, it is a function that takes an <tt>a</tt> and returns an action that, when performed, produces an <tt>a</tt>. The action does not actually perform any real I/O and the value it yields is simply the one passed as the argument. Actions from <tt>return</tt> are often used as the last step of an action sequence to combine intermediate results into a bigger one. For example:</p>
<blockquote>
<pre><tt>getLinePair :: IO (String, String)
getLinePair = getLine &gt;&gt;= (\x -&gt;
                getLine &gt;&gt;= (\y -&gt;
                  return (x, y)))</tt></pre>
</blockquote>
<p>The meaning of this action is to read a first line from the terminal and then a second one. The result of the action is a pair of the first and the second line.</p>
<p>And that&#8217;s it. After this next steps could be to read about the &#8220;<tt>do</tt> notation&#8221; or to browse the documentation for the <a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/System-IO.html"><tt>System.IO</tt></a> package. If you enjoyed this tutorial or have any questions, feel free to post a comment below!</p>
<p>&#8211; raek</p>
<p>(Thanks to @kajgo and @ricli85 for proofreading!)</p>
<p><a class="FlattrButton" style="display:none;" href="http://blog.raek.se/2012/10/19/haskell-io-in-five-minutes/"></a><noscript><a href="http://flattr.com/thing/949030/Haskell-IO-in-Five-Minutes" target="_blank"><img src="http://api.flattr.com/button/flattr-badge-large.png" alt="Flattr this" title="Flattr this" border="0" /></a></noscript></p>
<ol class="footnotes"><li id="footnote_0_282" class="footnote">This is not true at the top level of the GHCi command-line since it handles I/O actions specially compared to other values.</li><li id="footnote_1_282" class="footnote">This is read as &#8220;unit&#8221; and means &#8220;no useful value&#8221;.</li><li id="footnote_2_282" class="footnote">In reality, the <tt>(&gt;&gt;=)</tt> and <tt>return</tt> functions do actually involve <em>a more general type</em> than <tt>IO</tt>.</li></ol>]]></content:encoded>
			<wfw:commentRss>http://blog.raek.se/2012/10/19/haskell-io-in-five-minutes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Running Eagle 6.0/6.1/6.2 in 32/64-bit Ubuntu GNU/Linux</title>
		<link>http://blog.raek.se/2012/01/06/running-cadsoft-eagle-version-6-in-ubuntu-gnulinux/</link>
		<comments>http://blog.raek.se/2012/01/06/running-cadsoft-eagle-version-6-in-ubuntu-gnulinux/#comments</comments>
		<pubDate>Thu, 05 Jan 2012 23:33:31 +0000</pubDate>
		<dc:creator>raek</dc:creator>
				<category><![CDATA[Electronics]]></category>
		<category><![CDATA[Eagle]]></category>
		<category><![CDATA[Ubuntu]]></category>

		<guid isPermaLink="false">http://blog.raek.se/?p=264</guid>
		<description><![CDATA[CadSoft recently released version 6 of its PCB layout program Eagle. You want to use it in Ubuntu? Here's how to get it working.]]></description>
			<content:encoded><![CDATA[<p><em>Update: Eagle 6.2.0 has been released. The issue remains though and this updated guide still applies.</em></p>
<p><em>Minor update: Changed instructions to download libpng source code via FTP instead of Git. This results in one less needed tool and a decreased download size.</em></p>
<p><em>Update: This guide has been revised to work on both 32-bit and 64-bit systems. Previously it only worked on 32-bit systems. Please write a comment if you have any questions or find something that does not work.</em></p>
<p><em>Update: Eagle 6.1.0 has been released! This guide still applies to both 6.0.0 and 6.1.0, and has been updated with the following change: The string &#8220;6.0&#8243; has been replaced by &#8220;6.1&#8243; in the name of the installer and in the installation location. Apart from that everything is the same.</em></p>
<p>CadSoft recently released version 6 of its PCB layout program Eagle. So, you wanted to use it in Ubuntu? The <code>eagle</code> package in Ubuntu is only version 5.11.0 as of Oneiric, so you downloaded the new version from <a href="http://www.cadsoftusa.com/">the official website</a>? You ran the installer and got this error?</p>
<pre><code>error while loading shared libraries: libpng14.so.14: cannot open shared object file: No such file or directory
</code></pre>
<p>It turns out that Eagle needs newer versions of some libraries than are available in the Ubuntu repos. This post will show you how to get hold of these specific version and how set them up with Eagle.</p>
<p><em>No super user access is needed (besides from installing build tools) in the approach I chose. The special versions of the libraries are only used Eagle and will never cause trouble for any other applications you have installed, because the system directories are never touched.</em></p>
<h2>Overview</h2>
<p>My approach was to download the source for all libraries Eagle needs, compile them (as 32-bit, since that&#8217;s what Eagle requires), install them in a local directory, and make a small script to launch Eagle. The libraries Eagle needs are:</p>
<ul>
<li><a href="http://www.libpng.org/pub/png/libpng.html">libpng</a> 1.4.x (provides <code>libpng14.so</code>)</li>
<li><a href="http://www.openssl.org/">OpenSSL</a> 1.0.0 (provides <code>libssl.so.1.0.0</code> and <code>libcrypto.so.1.0.0</code>)</li>
<li><a href="http://www.ijg.org/">libjpeg</a> v8 (provides <code>libjpeg.so.8</code>)</li>
</ul>
<h2>Preparations</h2>
<p>In my setup I put all relevant files the directory <code>/home/raek/.eagle</code> . To follow my steps you need to create your own directory and subsitute its path it for  <code>/home/raek/.eagle</code> in all the following steps.</p>
<pre><code>mkdir /home/raek/.eagle
cd /home/raek/.eagle
</code></pre>
<p>I had to install some tools and libraries were needed in the process. This depended on whether I was on my 32-bit or 64-bit machine. In the 32-bit scenario they were:</p>
<pre><code>sudo apt-get install build-essential perl
sudo apt-get install zlib1g zlib1g-dev
</code></pre>
<p>And in the 64-bit they were:</p>
<pre><code>sudo apt-get install build-essential perl gcc-multilib
sudo apt-get install ia32-libs lib32z1 lib32z1-dev
</code></pre>
<h2>Downloading, building, and installing libraries locally</h2>
<p>I went about to install a typical library like this:</p>
<ol>
<li>Download the source code and unpack it.</li>
<li>Configure the library with suitable options.</li>
<li>Build the library.</li>
<li>Test the library.</li>
<li>Install the library.</li>
<li>Verify that the expected <code>.so</code> file shows up in<br />
   <code>/home/raek/.eagle/usr/lib</code> and that is 32-bit.</li>
</ol>
<p>Of the configure options, the <code>--prefix=/home/raek/.eagle/usr</code> option is important since it tells the build system where to put the files when <code>make install</code> is run. It allowed me to put the result my own <code>usr</code> directory rather than in the system-wide <code>/usr</code> or <code>/usr/local</code>.</p>
<p>The <code>CFLAGS=-m32</code> option (in its various forms) is also needed to force the libraries to be built in 32-bit form.</p>
<p>I verified that the resulting <code>.so</code> files were in the right place and 32-bit with the <code>file -L</code> command. If it was 32-bit the command came back with &#8220;ELF 32-bit&#8221;, if was 64-bit it came back with &#8220;ELF 64-bit&#8221;, and if the file didn&#8217;t exist at all it came back with &#8220;No such file or directory&#8221;.</p>
<h3>libpng 1.4.x</h3>
<p>I downloaded the <code>libpng14</code> source code and configured, built, tested, installed and verified it:</p>
<pre><code>wget http://www.sourceforge.net/projects/libpng/files/libpng14/older-releases/1.4.11/libpng-1.4.11.tar.gz
tar zxf libpng-1.4.11.tar.gz
cd libpng-1.4.11
./configure --prefix=/home/raek/.eagle/usr CFLAGS=-m32
make check
make install
cd ..
file -L usr/lib/libpng14.so
</code></pre>
<h3>libssl 1.0.0</h3>
<p>The libssl install procedure was very similar, but here the <code>shared</code> option was needed to generate <code>.so</code> files:</p>
<pre><code>wget http://www.openssl.org/source/openssl-1.0.0f.tar.gz
tar zxf openssl-1.0.0f.tar.gz
cd openssl-1.0.0f
./Configure shared --prefix=/home/raek/.eagle/usr linux-generic32 -m32
make
make test
make install
cd ..
file -L usr/lib/libssl.so.1.0.0
file -L usr/lib/libcrypto.so.1.0.0
</code></pre>
<h3>libjpeg v8</h3>
<p>No surprises here:</p>
<pre><code>wget http://www.ijg.org/files/jpegsrc.v8c.tar.gz
tar zxf jpegsrc.v8c.tar.gz
cd jpeg-8c
./configure --prefix=/home/raek/.eagle/usr CFLAGS=-m32
make
make test
make install
cd ..
file -L usr/lib/libjpeg.so.8
</code></pre>
<h2>Installing Eagle</h2>
<p>I now had all the library files I needed in my <code>/home/raek/.eagle/usr/lib</code> directory and proceeded with downloading and installing Eagle itself. I told the shared library loader to always look for libraries in this directory first by setting the <code>LD_LIBRARY_PATH</code> environment variable in my shell session.</p>
<p>I could then run the Eagle installer and chose to install Eagle in <code>/home/raek/.eagle/eagle-6.2.0</code> . After that I could start eagle by running the binary found in <code>eagle-6.2.0/bin/eagle</code>.</p>
<pre><code>wget ftp://ftp.cadsoft.de/eagle/program/6.2/eagle-lin-6.2.0.run
export LD_LIBRARY_PATH=/home/raek/.eagle/usr/lib
sh eagle-lin-6.2.0.run
/home/raek/.eagle/eagle-6.2.0/bin/eagle
</code></pre>
<h2>Making a Launch Script</h2>
<p>Starting eagle worked fine, but I din&#8217;t want to have to run the <code>export</code> command in a terminal each time I were going to start Eagle. Therefore I made a small script with the following contents:</p>
<pre><code>#!/bin/sh
export LD_LIBRARY_PATH=/home/raek/.eagle/usr/lib
/home/raek/.eagle/eagle-6.2.0/bin/eagle
</code></pre>
<p>After I wrote the script I made it executable and added a symlink to it in my <code>.bin</code> directory, which I have on my <code>PATH</code>.</p>
<pre><code>nano run_eagle.sh
chmod a+x run_eagle.sh
cd /home/raek/.bin
ln -s /home/raek/.eagle/run_eagle.sh /home/raek/.bin/eagle
</code></pre>
<p>I can now start Eagle by just running <code>eagle</code>! If I want to uninstall Eagle some time in the future, all I need to do is to delete <code>/home/raek/.eagle</code> and <code>/home/raek/.bin/eagle</code> and both Eagle and the special version libraries will be gone.</p>
<p>And that&#8217;s it! Please drop a comment below if this was useful for you (or if if something turned out to not work)!</p>
<p><a class="FlattrButton" style="display: none;" href="http://blog.raek.se/2012/01/06/running-cadsoft-eagle-version-6-in-ubuntu-gnulinux/"></a><noscript><a href="http://flattr.com/thing/461384/Running-CadSoft-Eagle-Version-6-in-Ubuntu-GNULinux" target="_blank"><img src="http://api.flattr.com/button/flattr-badge-large.png" alt="Flattr this" title="Flattr this" border="0" /></a></noscript></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.raek.se/2012/01/06/running-cadsoft-eagle-version-6-in-ubuntu-gnulinux/feed/</wfw:commentRss>
		<slash:comments>55</slash:comments>
		</item>
		<item>
		<title>The re- functions</title>
		<link>http://blog.raek.se/2011/06/17/the-re-functions/</link>
		<comments>http://blog.raek.se/2011/06/17/the-re-functions/#comments</comments>
		<pubDate>Fri, 17 Jun 2011 15:18:05 +0000</pubDate>
		<dc:creator>raek</dc:creator>
				<category><![CDATA[Clojure]]></category>

		<guid isPermaLink="false">http://blog.raek.se/?p=242</guid>
		<description><![CDATA[I recently realized that of the core Clojure regex functions (re-pattern, re-matcher, re-matches, re-groups, re-find, re-seq) I was completely unaware of how re-matcher, re-matches, re-groups were supposed to be used. Their names hint that they are useful for something, but I had never needed to use them. To understand them, I first had to dive into the Javadoc a bit, more specifically the java.util.regex package.]]></description>
			<content:encoded><![CDATA[<p>I recently realized that of the core Clojure regex functions (<tt>re-pattern</tt>, <tt>re-matcher</tt>, <tt>re-matches</tt>, <tt>re-groups</tt>, <tt>re-find</tt>, <tt>re-seq</tt>) I was completely unaware of how <tt>re-matcher</tt>, <tt>re-matches</tt>, <tt>re-groups</tt> were supposed to be used. Their names hint that they are useful for something, but I had never needed to use them. To understand them, I first had to dive into the Javadoc a bit, more specifically the <tt><a href="http://download.oracle.com/javase/6/docs/api/java/util/regex/package-summary.html">java.util.regex</a></tt> package.</p>
<p>The are two basic concepts in the regex package: the <tt>Pattern</tt> and the <tt>Matcher</tt>. A Pattern is what a Clojure regex literal produces and <tt>(re-pattern </tt><i>pattern-string</i><tt>)</tt> can be used to create one from a string.</p>
<blockquote><pre><tt>user=&gt; <b>(def p (re-pattern "abc|def"))</b>
#'user/p</tt></pre>
</blockquote>
<p>A <tt>Matcher</tt> is a stateful class used to find one or more matching (sub)sequences of a string. A matcher can be created with <tt>(re-matcher </tt><i>pattern</i><tt> </tt><i>string</i><tt>)</tt> and is initially in a state where the match region is the whole string.</p>
<blockquote><pre><tt>user=&gt; <b>(def m (re-matcher p "defabc"))</b>
#'user/m</tt></pre>
</blockquote>
<p>There are two methods for trying to match the region against the pattern: <tt>(.find </tt><i>matcher</i><tt>)</tt> and <tt>(.matches </tt><i>matcher</i><tt>)</tt>. Here, &#8220;matches&#8221; should be read as in &#8220;it matches&#8221; and not &#8220;the matches&#8221;. The methods alter the state of the <tt>Matcher</tt> in the following way: if the beginning of the region matches the pattern, then true is returned and the the matched substring is stored internally and popped off the beginning of the remaining match region. Otherwise false is returned. The two methods differ in that <tt>.find</tt> will scan the string for a match but <tt>.matches</tt> requires the whole remaining region to match.</p>
<blockquote><pre><tt>user=&gt; <b>(.find m)</b>
true</tt></pre>
</blockquote>
<p>To extract the matched subsequence (or the matched groups) for the most recent match, <tt>re-groups</tt> is used. If no groups are present in the patter, the match is returned as a string. If <i>n</i> groups are present in the pattern, a vector of size <i>n+1</i> is returned, where the first element is the whole match and the rest the matches of the groups. The state of the <tt>Matcher</tt> remains unchanged.</p>
<blockquote><pre><tt>user=&gt; <b>(re-groups m)</b>
"def"
user=&gt; <b>(re-groups m)</b>
"def"
user=&gt; <b>(.find m)</b>
true
user=&gt; <b>(re-groups m)</b>
"abc"
user=&gt; <b>(.find m)</b>
false</tt></pre>
</blockquote>
<p>The <tt>re-find</tt> function is a wrapper for <tt>.find</tt> that in addition to accept a <tt>Matcher</tt> as an argument can also take a pattern and a string and create its own <tt>Matcher</tt>. A call like (<tt>re-find </tt><i>pattern</i><tt> </tt><i>string</i><tt>)</tt> is equivalent to <tt>(let [m (re-matcher </tt><i>pattern</i><tt> </tt><i>string</i><tt>)] (when (.find m) (re-groups m)))</tt>.</p>
<blockquote><pre><tt>user=&gt; <b>(re-find #"abc|def" "xdefabcy")</b>
"def"</tt></pre>
</blockquote>
<p>The <tt>re-matches</tt> function works just like <tt>re-find</tt>, except that it uses the <tt>.matches</tt> method and does not come with a single argument variant (that would take a <tt>Matcher</tt>).</p>
<blockquote><pre><tt>user=&gt; <b>(re-matches #"abc|def" "def")</b>
"def"
user=&gt; <b>(re-matches #"abc|def" "defabc")</b>
nil</tt></pre>
</blockquote>
<p>In addition, there&#8217;s the <tt>re-seq</tt> function that returns a sequence of all the matches <tt>re-find</tt> would find. It accepts a pattern and a string as its arguments: <tt>(re-seq </tt><i>pattern</i><tt> </tt><i>string</i><tt>)</tt>.</p>
<blockquote><pre><tt>user=&gt; <b>(re-seq #"abc|def" "xdefabcy")</b>
("def" "abc")</tt></pre>
</blockquote>
<p>In the end, four of the functions turn out to be more useful than the others for a Clojure programmer:</p>
<ul>
<li>To create a regex pattern from a string, use <tt>re-pattern</tt>.</li>
<li>To match a string completely against a pattern, use <tt>re-matches</tt>.</li>
<li>To find some part of a string that matches a pattern, use <tt>re-find</tt>.</li>
<li>To find all the parts of a string that matches a pattern, use <tt>re-seq</tt>.</li>
</ul>
<p><a class="FlattrButton" style="display:none;" href="http://blog.raek.se/2011/06/17/the-re-functions/"></a><br />
<noscript><a href="http://flattr.com/thing/313567/The-re-functions" target="_blank"><br />
<img src="http://api.flattr.com/button/flattr-badge-large.png" alt="Flattr this" title="Flattr this" border="0" /></a></noscript></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.raek.se/2011/06/17/the-re-functions/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Getting Started with Clojure Development I: The REPL</title>
		<link>http://blog.raek.se/2011/04/20/getting-started-with-clojure-development-i-the-repl/</link>
		<comments>http://blog.raek.se/2011/04/20/getting-started-with-clojure-development-i-the-repl/#comments</comments>
		<pubDate>Tue, 19 Apr 2011 22:14:59 +0000</pubDate>
		<dc:creator>raek</dc:creator>
				<category><![CDATA[Clojure]]></category>

		<guid isPermaLink="false">http://blog.raek.se/?p=173</guid>
		<description><![CDATA[This is the first post of one my ongoing attempt to write a series of blog posts about how to get started with development in Clojure. This post will cover a beginner's first encounter with the Clojure Read Eval Print Loop.]]></description>
			<content:encoded><![CDATA[<p><em>This is the first post of one my ongoing attempt to write a series of blog posts about how to get started with development in Clojure. This post will cover a beginner&#8217;s first encounter with the Clojure Read Eval Print Loop.</em></p>
<p><em>This post assumes a UNIX-like environment. Some details might vary from OS to OS (especially for Windows). In those cases, study the documentation</em><em> related to your platform </em><em> for the mentioned applications.<br />
</em></p>
<p><strong>So, you&#8217;ve heard some interesting things about this language called Clojure&#8230;</strong> Good. When you play around with an <em>interactive</em> programming language (which Clojure is a prime example of) you usually do it though a shell of some sort. In Lisp languages, this shell is traditionally called the REPL, which stands for Read Eval Print Loop.</p>
<p>The question I can almost hear you think is: <strong>&#8220;How do I install Clojure?&#8221;</strong> The answer to that question, which is somewhat unusual, is: <strong>&#8220;You don&#8217;t.&#8221;</strong> Clojure&#8217;s approach to language and library versions is similar to Virtualenv of Python or RVM of Ruby. To launch Clojure you use what&#8217;s usually called a build tool. Since they do more than just build tasks, so you can think of them as &#8220;Clojure environment tools&#8221;. Two of the most common ones are Leiningen and Cake. Here, I will only cover Leiningen, but Cake works nearly identically for basic tasks.</p>
<p>Now, what you <em>do</em> install is <strong>Leiningen</strong>:</p>
<ul>
<li>Download the <a href="https://github.com/technomancy/leiningen/raw/stable/bin/lein"><tt>lein</tt> script</a> available <a href="https://github.com/technomancy/leiningen">from the project page</a>.</li>
<li>Put the file in a directory where you keep executables. I keep mine in <tt>~/.bin/</tt></li>
<li>Make it executable: <tt>chmod a+x lein</tt></li>
<li>Ensure that directory with executables is on the PATH. I do this by having the following in my <tt>~/.profile</tt> file:
<pre><tt>PATH=$PATH:/home/raek/.bin
export PATH</tt></pre>
<p>This makes lein available both in applications started from Bash and in Gnome<sup><a href="http://blog.raek.se/2011/04/20/getting-started-with-clojure-development-i-the-repl/#footnote_0_173" id="identifier_0_173" class="footnote-link footnote-identifier-link" title="You might need to restart the X server for this change to be effective.">1</a></sup>; just change the <tt>/home/raek/</tt> to your own home directory.</li>
<li>Run <tt>lein</tt> once to let it download the files it needs. The files are placed in <tt>~/.lein</tt> and <tt>~/.m2</tt></li>
<li>Run <tt>lein repl</tt> to get a Clojure REPL!</li>
<li><em>Optional:</em> Install <tt>rlwrap</tt> using the package manager of your OS to get a better REPL experience. Otherwise JLine is used which does not support UTF-8.</li>
</ul>
<p>With a bare REPL in a terminal you can do much, but the lack of editing and saving abilities can make it tiresome in the long run. I therefore recommend to use an ordinary text editor to write the code and then send the code to the REPL. The simplest way to accomplish this is to simply copy and paste the code, but more sophisticated editors provide more convenient methods (I will shortly show this can done in Emacs).</p>
<p>Restricting oneself to only the REPL has some serious limitations and because of this I don&#8217;t recommend this approach in general, except for learning (for that it may indeed be very useful) and trivial projects. So far I  haven&#8217;t mentioned how divide code into multiple files, how to use  third party libraries or how to specify the version of Clojure to use. For that, you need to set up a Leiningen project. This is the topic for the next (upcoming) part of this blog post series.</p>
<p>In Emacs, you can interact with the REPL by following these steps:</p>
<ul>
<li>Install <tt>clojure-mode</tt> using <tt>package.el</tt> by following the instructions on the official <a href="http://dev.clojure.org/display/doc/Getting+Started+with+Emacs">Getting Started with Emacs</a> wiki page.</li>
<li>Execute <tt>M-x customize-variable RET inferior-lisp-program</tt> and configure it to use <tt>lein repl</tt> as the program.</li>
<li>Open a <tt>.clj</tt> file, or run <tt>M-x clojure-mode</tt> in a buffer (e.g. <tt>*scratch*</tt>).</li>
<li>Press <tt>C-c C-z</tt> to start the Clojure REPL.</li>
<li>Use <tt>C-x C-e</tt> at the end of an expresison to evaluate it or <tt>C-M-x</tt> to evaluate the expression spanning between the outermost parentheses surrounding the point.</li>
</ul>
<p>This is it for now. Happy hacking!</p>
<p>// raek</p>
<p><a class="FlattrButton" style="display:none;" href="http://blog.raek.se/2011/04/20/getting-started-with-clojure-development-i-the-repl/"></a><br />
<noscript><a href="http://flattr.com/thing/171408/Getting-Started-with-Clojure-Development-I-The-REPL" target="_blank"><br />
<img src="http://api.flattr.com/button/flattr-badge-large.png" alt="Flattr this" title="Flattr this" border="0" /></a></noscript></p>
<ol class="footnotes"><li id="footnote_0_173" class="footnote">You might need to restart the X server for this change to be effective.</li></ol>]]></content:encoded>
			<wfw:commentRss>http://blog.raek.se/2011/04/20/getting-started-with-clojure-development-i-the-repl/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Executors in Clojure</title>
		<link>http://blog.raek.se/2011/01/24/executors-in-clojure/</link>
		<comments>http://blog.raek.se/2011/01/24/executors-in-clojure/#comments</comments>
		<pubDate>Mon, 24 Jan 2011 18:21:47 +0000</pubDate>
		<dc:creator>raek</dc:creator>
				<category><![CDATA[Clojure]]></category>

		<guid isPermaLink="false">http://blog.raek.se/?p=5</guid>
		<description><![CDATA[Java has a very useful package called java.util.concurrent, which contains classes and interfaces for tasks, task execution tracking, thread-to-thread communication with blocking queues, locks, semaphores, atomic containers and the Executors Framework.  This blog post will walk you through the concepts of the Executors Framework as seen from Clojure. But first a word on the relationship [...]]]></description>
			<content:encoded><![CDATA[<p>Java has a very useful package called <tt>java.util.concurrent</tt>, which contains classes and interfaces for tasks, task execution tracking, thread-to-thread communication with blocking queues, locks, semaphores, atomic containers and the Executors Framework.  This blog post will walk you through the concepts of the Executors Framework as seen from Clojure.</p>
<p>But first a word on the relationship between Clojure and existing Java frameworks. Clojure has been designed to make Java interop as seamless as possible. Where Java is not broken, Clojure does not in general<sup><a href="http://blog.raek.se/2011/01/24/executors-in-clojure/#footnote_0_5" id="identifier_0_5" class="footnote-link footnote-identifier-link" title="An exception is the clojure.string namespace, which got added in Clojure 1.2.">1</a></sup> add a wrapping layer.<sup><a href="http://blog.raek.se/2011/01/24/executors-in-clojure/#footnote_1_5" id="identifier_1_5" class="footnote-link footnote-identifier-link" title="http://clojure-log.n01se.net/date/2010-12-02.html#17:53">2</a></sup></p>
<p>The Executors Framework provides abstractions for representing tasks, handles to running tasks and executors as objects. In Java, general tasks (or units of work) are contained in instances of <a title="Javadoc for java.lang.Runnable" href="http://download.oracle.com/javase/6/docs/api/java/lang/Runnable.html"><tt>Runnable</tt></a> or <a title="Javadoc for java.util.concurrent.Callable" href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Callable.html"><tt>Callable</tt></a>. A task is executed by calling its <tt>run</tt> and <tt>call</tt> method respectively. The interfaces are very straight forward<sup><a href="http://blog.raek.se/2011/01/24/executors-in-clojure/#footnote_2_5" id="identifier_2_5" class="footnote-link footnote-identifier-link" title="When in Clojure, you can think of type parameters as being of type Object.">3</a></sup> :</p>
<blockquote>
<pre><tt>package java.lang;
public interface Runnable {
    void run();
}</tt></pre>
</blockquote>
<blockquote>
<pre><tt>package java.util.concurrent;
public interface Callable&lt;V&gt; {
    V call();
}</tt></pre>
</blockquote>
<p>The difference between them is that <tt>call</tt> can return a value, unlike <tt>run</tt> which is of type void. As you might have realized, this abstraction is a bit similar to function objects: They are both ways of encapsulating pieces of code as objects. Naturally, Clojure functions implement <tt>Runnable</tt> and <tt>Callable</tt> by invoking itself with zero arguments:</p>
<blockquote>
<pre><tt>user=&gt; <strong>(defn demo-task []
         (println "boo!")
         123)</strong>
#'user/demo-task
user=&gt; <strong>(.run demo-task)</strong>
boo!
nil
user=&gt; <strong>(.call demo-task)</strong>
boo!
123</tt></pre>
</blockquote>
<p>Now that we have a way of describing tasks, we can explore how we can pass them to something that can execute them. The simplest abstraction for this is the <a title="Javadoc for java.util.concurrent.Executor" href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Executor.html"><tt>Executor</tt></a>. It has one method called <tt>execute</tt> that takes a <tt>Runnable</tt>. When it is invoked, the <tt>Executor</tt> is expected to execute the task some time in the future.</p>
<blockquote>
<pre><tt>package java.util.concurrent;
public interface Executor {
    void execute(Runnable command);
}</tt></pre>
</blockquote>
<p>For fun, we can now implement an <tt>Executor</tt> that when passed a task creates a dedicated thread for it and runs the tasks in it:</p>
<blockquote>
<pre><tt>user=&gt; <strong>(defn create-thread-executor []
         (reify
           java.util.concurrent.Executor
           (execute [_ task]
             (let [f #(try
                        (task)
                        ;; return value is ignored by Thread
                        (catch Throwable e
                          ;; not much we can do here
                          (.printStackTrace e *out*)))]
               (doto (Thread. f)
                 (.start))))))</strong>
#'user/create-thread-executor
user=&gt; <strong>(alter-var-root #'*out* (constantly *out*))</strong><sup><a href="http://blog.raek.se/2011/01/24/executors-in-clojure/#footnote_3_5" id="identifier_3_5" class="footnote-link footnote-identifier-link" title="This makes the current repl the default output stream for new threads.">4</a></sup>
#&lt;PrintWriter java.io.PrintWriter@16c72cc&gt;
user=&gt; <strong>(def exe (create-thread-executor))</strong>
#'user/exe
user=&gt; <strong>(.execute exe demo-task)</strong>
boo!
nil</tt></pre>
</blockquote>
<p>There are three things that the above code does not address very well: it doesn&#8217;t tell you when the task is done, it does not provide a way of getting back any value and it does not provide a way for the calling code to detect a failure in the task. A much richer abstraction is the <a title="Javadoc for java.util.concurrent.ExecutorService" href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html"><tt>ExecutionService</tt></a>. It extends the <tt>Executor</tt> interface and provides methods to get a result back from a task, submit multiple tasks at once and to gracefully shut it down: ﻿<tt>awaitTermination</tt>, <tt>invokeAll</tt>, <tt>invokeAny</tt>, <tt>isShutdown</tt>, <tt>isTerminated</tt>, <tt>shutdown</tt>, <tt>shutdownNow</tt> and <tt>submit</tt>. Since it allows tasks to communicate a value back, tasks can be of type <tt>Callable</tt>.</p>
<p>Along with the <tt>ExecutorService</tt>, another concept is introduced: the <a title="Javadoc for java.util.concurrent.Future" href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html"><tt>Future</tt></a>. An object that implements this interface represent a handle to a task that is queued, cancelled, being executed or has been scheduled for execution. When you submit a task to an <tt>ExecutorService</tt>, you get a <tt>Future</tt> back. You can use it to retrieve its result, query whether it&#8217;s done yet, or cancel it, among other things. Its interface is as follows:</p>
<blockquote>
<pre><tt>package java.util.concurrent;
public interface Future&lt;V&gt; {
    boolean cancel(boolean mayInterruptIfRunning);
    V get();
    V get(long timeout, TimeUnit unit);
    boolean isCancelled();
    boolean isDone();
}</tt></pre>
</blockquote>
<p>When invoking the <tt>get</tt> method, the call will block until the task is done or the call times out (if a timeout was given). Clojure provides wrapper functions (whose names begin with <tt>future-</tt>), for all of these methods except for <tt>get</tt>. (You can still access those methods with usual Java interop.) A call to <tt>get</tt> can exit in five ways:</p>
<ul>
<li>On sucess, it returns the result of the <tt>call</tt> method of the task, if it was a <tt>Callable</tt>, or <tt>nil</tt>, if it was a <tt>Runnable</tt>.</li>
<li>If the <tt>Future</tt> has been cancelled, a <tt>CancellationException</tt> is thrown.</li>
<li>If the body of the task has thrown an unhandled exception, an <tt>ExecutionException</tt> is thrown with that exception as its cause.</li>
<li>If the thread that executed the task has been interrupted, an <tt>InterruptedException</tt> is thrown.</li>
<li>If a timeout was given and that time has passed, a <tt>TimeoutException</tt> is thrown</li>
</ul>
<p>In addition, the Executors Framework provides the <a title="Javadoc for java.util.concurrent.Executors" href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Executors.html"><tt>Executors</tt></a> class, which is a colletion of static factory methods for creating various concrete instances of <tt>ExecutorService</tt>. Two very useful ones are <tt>newFixedThreadPool</tt> and <tt>newCachedThreadPool</tt>. Using thread pools is usually a good idea, since thread creation is an expensive operation.</p>
<p><tt>newFixedThreadPool</tt> solves the problem by creating a fixed number of threads, and using them to execute the tasks. The cost for creating new threads only occurs once, but only a fixed number of tasks can be run at the same time. The approach of <tt>newCachedThreadPool</tt> is to start with no threads and creates new ones as it needs them. If a thread is done with its task, it will stay around for sixty seconds. If it does not get a new task in that time, it will be deallocated. Let&#8217;s try using the first kind from Clojure:</p>
<blockquote>
<pre><tt>user=&gt; <strong>(import 'java.util.concurrent.Executors)</strong>
java.util.concurrent.Executors
user=&gt; <strong>(def pool (Executors/newFixedThreadPool 4))</strong>
#'user/create-thread-executor
user=&gt; <strong>(defn sleep-print-and-double [x]
         (Thread/sleep 1000)
         (println x "done!")
         (* x 2))</strong>
#'user/sleep-and-print
user=&gt; <strong>(let [tasks (for [i (range 10)]
                     #(sleep-print-and-double i))
             futures (.invokeAll pool tasks)]
         (for [ftr futures]
           (.get ftr)))</strong>
;; (1 sec delay)
0 done!
1 done!
3 done!
2 done!
;; (1 sec delay)
4 done!
5 done!
7 done!
6 done!
;; (1 sec delay)
8 done!
9 done!
(0 2 4 6 8 10 12 14 16 18)
</tt></pre>
</blockquote>
<p>Not too complicated, wasn&#8217;t it? I will finish by describing a macro in Clojure that you might have heard of: <tt>future</tt>. (The name itself may be a bit unfortunate, since it only tells us that we get a <tt>Future</tt> object, but not what took care of the task.) <tt>future</tt> takes some expressions, wraps them up as the body of an anonymous function and passed that function to <tt>future-call</tt>. In other words, <tt>(future (foo) (bar))</tt> is just a more convenient way of writing <tt>(future-call (fn [] (foo) (bar)))</tt>.</p>
<p><tt>future-call</tt>, the function that actually does the work, submits the given task to one of Clojure&#8217;s internal thread pools<sup><a href="http://blog.raek.se/2011/01/24/executors-in-clojure/#footnote_4_5" id="identifier_4_5" class="footnote-link footnote-identifier-link" title="This happens to be the same one used by the implementation of send-off">5</a></sup> and gets a <tt>Future</tt> back. Another object that implements both <tt>IDeref</tt> (which allows you to call deref/@ on it) and <tt>Future</tt> will be the actual return value. Dereferencing it will invoke the <tt>get</tt> method of the <tt>Future</tt> from the thread pool and any call to a <tt>Future</tt> method on it will be delegated to that <tt>Future</tt> too. All this is perhaps best clarified with the source code itself:</p>
<blockquote>
<pre><tt>(defn future-call [^Callable f]
  (let [fut (.submit clojure.lang.Agent/soloExecutor f)]
    (reify
     clojure.lang.IDeref
      (deref [_] (.get fut))
     java.util.concurrent.Future
      (get [_] (.get fut))
      (get [_ timeout unit] (.get fut timeout unit))
      (isCancelled [_] (.isCancelled fut))
      (isDone [_] (.isDone fut))
      (cancel [_ interrupt?] (.cancel fut interrupt?)))))</tt></pre>
</blockquote>
<p><tt>future</tt> provides a fairly simple standard solution for starting off some piece of code in another thread and you are likely to come across it. Now you know how it works under the hood.</p>
<p>// raek<br />
<a class="FlattrButton" style="display:none;" href="http://blog.raek.se/2011/01/24/executors-in-clojure/"></a><br />
<noscript><a href="http://flattr.com/thing/123570/Executors-in-Clojure" target="_blank"><br />
<img src="http://api.flattr.com/button/flattr-badge-large.png" alt="Flattr this" title="Flattr this" border="0" /></a></noscript></p>
<ol class="footnotes"><li id="footnote_0_5" class="footnote">An exception is the clojure.string namespace, which got added in Clojure 1.2.</li><li id="footnote_1_5" class="footnote"><a href="http://clojure-log.n01se.net/date/2010-12-02.html#17:53">http://clojure-log.n01se.net/date/2010-12-02.html#17:53</a></li><li id="footnote_2_5" class="footnote">When in Clojure, you can think of type parameters as being of type Object.</li><li id="footnote_3_5" class="footnote">This makes the current repl the default output stream for new threads.</li><li id="footnote_4_5" class="footnote">This happens to be the same one used by the implementation of <tt>send-off</tt></li></ol>]]></content:encoded>
			<wfw:commentRss>http://blog.raek.se/2011/01/24/executors-in-clojure/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
