<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><feed xmlns="http://www.w3.org/2005/Atom">
    <title>Jacob Stanley « Blog</title>
    
    <link href="http://jacob.stanley.io" />
    <id>http://jacob.stanley.io/atom.xml</id>
    <author>
        <name>Ceiling cat is watching you unsafePerformIO</name>
    </author>
    <updated>2010-10-27T00:00:00Z</updated>
    <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/atom+xml" href="http://feeds.feedburner.com/jacobstanley" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="jacobstanley" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><entry>
    <title>'sudo gem install ...' behind a proxy</title>
    <link href="http://jacob.stanley.io/2010/10/27/sudo-gem-install-behind-a-proxy/" />
    <id>http://jacob.stanley.io/2010/10/27/sudo-gem-install-behind-a-proxy/</id>
    <updated>2010-10-27T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p><em>This post applies to Ubuntu Server 10.10 (Maverick Meerkat)</em></p>
<p>I had some trouble installing gems (as root) behind our corporate proxy server today.</p>
<pre class="sourceCode"><code>$ sudo gem install rake
ERROR:  http://rubygems.org/ does not appear to be a repository
ERROR:  Could not find a valid gem 'rake' (&gt;= 0) in any repository
</code></pre>
<p>This is despite the fact that my <code>http_proxy</code> environment variable had been set in my <code>~/.bashrc</code> file.</p>
<pre class="sourceCode"><code class="sourceCode bash"><span class="co"># ~/.bashrc: executed by bash(1) for non-login shells.</span><br /><br /><span class="co"># HTTP Proxy</span><br /><span class="kw">export</span> <span class="ot">http_proxy=</span>http://username:password@192.168.0.1:80/<br /><br /><span class="co"># ...</span></code></pre>
<p>It turns out that you need to do some tweaking if you want <code>sudo</code> to carry your proxy environment across from the current user. To do this, run <code>sudo visudo</code> and add the <code>env_keep</code> line below:</p>
<pre class="sourceCode"><code class="sourceCode bash"><span class="co"># /etc/sudoers</span><br /><span class="co">#</span><br /><span class="co"># This file MUST be edited with the 'visudo' command as root.</span><br /><span class="co">#</span><br /><span class="co"># See the man page for details on how to write a sudoers file.</span><br /><span class="co">#</span><br /><br />Defaults        env_reset<br />Defaults        env_keep += <span class="st">&quot;http_proxy https_proxy ftp_proxy&quot;</span></code></pre>
<p>Once you’re done editing, press <code>Ctrl+X</code> to exit, then <code>Y</code> to save your changes and make sure you save them to <code>/etc/sudoers</code> and not <code>/etc/sudoers.tmp</code> like it suggests. Press <code>Y</code> when it asks if you want to overwrite.</p>
<p>Now everything should be sweet. You can check that the environment is propagating using env.</p>
<pre class="sourceCode"><code>$ sudo env | grep http_proxy
http_proxy=http://username:password@192.168.0.1:80/
</code></pre>
<p>And finally…</p>
<pre class="sourceCode"><code>$ sudo gem install rake
Successfully installed rake-0.8.7
1 gem installed
Installing ri documentation for rake-0.8.7...
Installing RDoc documentation for rake-0.8.7...
</code></pre>]]></summary>
</entry>
<entry>
    <title>Installing Gtk2Hs 0.11 on Windows</title>
    <link href="http://jacob.stanley.io/2010/10/20/installing-gtk2hs-on-windows/" />
    <id>http://jacob.stanley.io/2010/10/20/installing-gtk2hs-on-windows/</id>
    <updated>2010-10-20T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>This is a quick to note to myself about what I had to do to install <a href="http://haskell.org/gtk2hs/">Gtk2Hs</a> 0.11 on Windows, but others might find it useful as well.</p>
<h2 id="installing-gtk">Installing GTK+</h2>
<p>Download the GTK+ all-in-one bundle from <a href="http://www.gtk.org/download-windows.html">here</a>. I used 2.16 because I had some problems with libpng <a href="#libpng">[1]</a> and zlib <a href="#zlib">[2]</a> when I tried 2.22.</p>
<p>Extract it somewhere without spaces in the name, and add the <code>\bin</code> directory to your PATH. I extracted the bundle to <code>c:\gtk-2.16</code> so I had to add <code>c:\gtk-2.16\bin</code> to my PATH.</p>
<p>You can check you’ve done this right by running <code>pkg-config</code> from the command line. You should get back something similar to this:</p>
<pre class="sourceCode"><code>&gt; pkg-config --cflags gtk+-2.0
-mms-bitfields -Ic:/gtk-2.16/include/gtk-2.0 -Ic:/gtk-2.16/lib...
</code></pre>
<h2 id="installing-gtk2hs">Installing Gtk2Hs</h2>
<p>Add the Haskell Platform’s <code>\mingw\bin</code> directory to your <code>PATH</code>. This was <code>C:\Program Files\Haskell Platform\2010.2.0.0\mingw\bin</code> in my case. I found this was necessary because the Gtk2Hs install requires <code>cpp.exe</code>, the C preprocessor.</p>
<p>Once you have all the prerequisites set up, installation is simply a <code>cabal install</code> away.</p>
<pre class="sourceCode"><code>&gt; cabal update
&gt; cabal install gtk2hs-buildtools
&gt; cabal install gtk
</code></pre>
<h2 id="testing-it-out">Testing it out</h2>
<p>You can try out your newly installed Gtk2Hs with the Hello World program from the <a href="http://www.haskell.org/gtk2hs/documentation/#hello_world">documentation</a>.</p>
<pre class="sourceCode"><code class="sourceCode haskell"><span class="kw">import</span> <span class="dt">Graphics.UI.Gtk</span><br /><br /><span class="ot">main </span><span class="ot">::</span> <span class="dt">IO</span> ()<br />main <span class="fu">=</span> <span class="kw">do</span><br />    initGUI<br />    window <span class="ot">&lt;-</span> windowNew<br />    button <span class="ot">&lt;-</span> buttonNew<br />    set window [ containerBorderWidth <span class="fu">:=</span> <span class="dv">10</span>,<br />                 containerChild <span class="fu">:=</span> button ]<br />    set button [ buttonLabel <span class="fu">:=</span> <span class="st">&quot;Hello World&quot;</span> ]<br />    onClicked button (<span class="fu">putStrLn</span> <span class="st">&quot;Hello World&quot;</span>)<br />    onDestroy window mainQuit<br />    widgetShowAll window<br />    mainGUI</code></pre>
<p>I was able to run the code above using <code>runghc</code> without any issues.</p>
<pre class="sourceCode"><code>&gt; runghc Hello.hs
</code></pre>
<div class="figure">
<img src="/img/gtk2hs-hello-world.png" title="Hello World with Gtk2Hs" /><p class="caption"></p>
</div>
<p>This gives us a window which is using the vanilla GTK+ theme. This looks a bit out of place on Windows and it’s easy to fix. Just add a <code>gtkrc</code> to your <code>\etc\gtk-2.0</code> directory (for me <code>c:\gtk-2.16\etc\gtk-2.0\gtkrc</code>) with the following contents:</p>
<pre class="sourceCode"><code>gtk-theme-name = &quot;MS-Windows&quot;
</code></pre>
<p>After adding a <code>gtkrc</code>, running our demo yields a much nicer looking window.</p>
<div class="figure">
<img src="/img/gtk2hs-hello-world-native.png" title="Native Hello World with Gtk2Hs" /><p class="caption"></p>
</div>
<h2 id="various-problems-i-encountered">Various problems I encountered</h2>
<p><span id="libpng">1.</span> If you’re trying to install using the GTK+ 2.22 bundle and you encounter this error:</p>
<pre class="sourceCode"><code>setup.exe: gtk-0.11.2: library-dirs: c:/devel/dist/win32/libpng-1.4.3-1/lib
doesn't exist or isn't a directory
</code></pre>
<p>It can easily be fixed by creating an empty directory in the location that setup.exe is searching for: <code>c:\devel\dist\win32\libpng-1.4.3-1\lib</code></p>
<p><span id="zlib">2.</span> Unfortunately, solving the libpng problem didn’t help me. I found that I was able to build and install the gtk package using cabal. The problem was that any programs which I built failed with an error about deflateSetHeader not being exported from zlib1.dll when I tried to run them.</p>]]></summary>
</entry>
<entry>
    <title>Installing Heist (and Hexpat) on Windows</title>
    <link href="http://jacob.stanley.io/2010/10/07/installing-heist-and-hexpat-on-windows/" />
    <id>http://jacob.stanley.io/2010/10/07/installing-heist-and-hexpat-on-windows/</id>
    <updated>2010-10-07T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p><em><strong>Edit:</strong> I’ve been in touch with Stephen Blackheath, the maintainer of <a href="http://hackage.haskell.org/package/hexpat">Hexpat</a>, and we’ve worked out a simple solution to this problem that looks promising. Hopefully by the time you read this Hexpat will install seamlessly via cabal, without the need for these instructions. I’ll leave the instructions below because it could be a week or two before all of this bubbles up to Heist.</em></p>
<p>So you’ve heard about <a href="http://snapframework.com">Snap</a>, that awesome new Haskell web framework, and you want to give it a try. You jump in to your Windows command prompt and cabal install snap-core and snap-server without any hassles, but when you try to install <a href="http://hackage.haskell.org/package/heist">Heist</a> you get this:</p>
<pre class="sourceCode"><code>&gt; cabal install heist
Resolving dependencies...
Configuring hexpat-0.18.3...
cabal: Missing dependency on a foreign library:
* Missing C library: expat
This problem can usually be solved by installing the system package that
provides this library (you may need the &quot;-dev&quot; version). If the library is
already installed but in a non-standard location then you can use the flags
--extra-include-dirs= and --extra-lib-dirs= to specify where it is.
cabal: Error: some packages failed to install:
heist-0.2.3 depends on hexpat-0.18.3 which failed to install.
hexpat-0.18.3 failed during the configure step. The exception was:
ExitFailure 1
</code></pre>
<p>Hmm, Heist depends on <a href="http://hackage.haskell.org/package/hexpat">Hexpat</a>, which has a dependency on a C library, <a href="http://expat.sourceforge.net">Expat</a>. Here you have two options, you can follow the instructions from the Hexpat documentation if you don’t mind hauling around a libexpat.dll with your application, or you can follow the instructions below for static linking.</p>
<p>First download <a href="/files/install-heist-mingw.zip">this zip file</a>. It contains the Expat dependencies you’ll need to install Hexpat, and a batch file which will do all the right stuff for you.</p>
<pre class="sourceCode"><code>bin\libexpat.dll
include\expat.h
include\expat_external.h
lib\libexpat.a
install-heist.bat
</code></pre>
<p>Extract it somewhere that you don’t mind keeping around, GHC will need these files every time it builds an executable that uses Hexpat/Heist. Now you can run <code>install-heist.bat</code> and everything should go smoothly this time:</p>
<pre class="sourceCode"><code>&gt; install-hexpat.bat
cabal install heist --extra-include-dirs=C:\hexpat\include --extra-lib-dirs=C:\hexpat\lib
Resolving dependencies...
Configuring hexpat-0.18.3...
Preprocessing library hexpat-0.18.3...
Building hexpat-0.18.3...

etc...
</code></pre>
<p>If you only need to run your Hexpat/Heist program from GHCi (or via <code>runghc</code>) then you’ll need to put <code>bin\libexpat.dll</code> in your <code>PATH</code> or in the current directory. If you don’t need GHCi then you can just delete the bin folder, it’s not used when building via GHC. When building using GHC Expat is static linked to your app, so there’s no need for extra dlls.</p>
<p>If you want to move the directory that your Expat dependencies are in, the easiest thing to do is to unregister heist and hexpat and follow the instructions again.</p>
<pre class="sourceCode"><code>&gt; ghc-pkg unregister heist
&gt; ghc-pkg unregister hexpat
</code></pre>]]></summary>
</entry>
<entry>
    <title>IP addresses and MAC addresses in Haskell</title>
    <link href="http://jacob.stanley.io/2010/08/12/ip-addresses-and-mac-addresses-in-haskell/" />
    <id>http://jacob.stanley.io/2010/08/12/ip-addresses-and-mac-addresses-in-haskell/</id>
    <updated>2010-08-12T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>When opening a socket, if you don’t specify the address of the network interface you want to listen on, you’ll actually be listening on all of them. In a secure environment, this isn’t always what you want. That said, it’s quite useful to be able to show an administrator of your system a drop down with the addresses of the various network interfaces available to the software.</p>
<p>When I set out to do this in Haskell I discovered that there wasn’t anything available that would let me get the address information for my network interfaces. So, I set out build <a href="http://hackage.haskell.org/package/network-info">network-info</a> and learned how to use the Foreign Function Interface (FFI) in the process.</p>
<p>Getting the IPv4, IPv6 and MAC addresses of your local network interfaces is now just a <code>cabal install</code> away:</p>
<pre class="sourceCode"><code>cabal install network-info
</code></pre>
<p>Once you’ve got the library installed it’s simple to get your network details:</p>
<pre class="sourceCode"><code class="sourceCode haskell"><span class="kw">import</span> <span class="dt">Network.Info</span><br /><br />main <span class="fu">=</span> <span class="kw">do</span><br />    ns <span class="ot">&lt;-</span> getNetworkInterfaces<br />    <span class="fu">mapM_</span> (<span class="fu">putStr</span> <span class="fu">.</span> showInterface) ns<br /><br />showInterface n <span class="fu">=</span> name n <span class="fu">++</span> <span class="st">&quot;\n&quot;</span><br />               <span class="fu">++</span> <span class="st">&quot;  IPv4: &quot;</span> <span class="fu">++</span> <span class="fu">show</span> (ipv4 n) <span class="fu">++</span> <span class="st">&quot;\n&quot;</span><br />               <span class="fu">++</span> <span class="st">&quot;  IPv6: &quot;</span> <span class="fu">++</span> <span class="fu">show</span> (ipv6 n) <span class="fu">++</span> <span class="st">&quot;\n&quot;</span><br />               <span class="fu">++</span> <span class="st">&quot;  MAC:  &quot;</span> <span class="fu">++</span> <span class="fu">show</span> (mac n) <span class="fu">++</span> <span class="st">&quot;\n&quot;</span></code></pre>
<p>Running this on my Ubuntu box yields something similar to this:</p>
<pre class="sourceCode"><code>$ runghc getaddr.hs
lo
  IPv4: 127.0.0.1
  IPv6: 0:0:0:0:0:0:0:1
  MAC:  00:00:00:00:00:00
eth0
  IPv4: 10.0.2.5
  IPv6: fe80:0:0:0:f00:15ff:fcf9:c677
  MAC:  08:00:72:5f:6c:19
</code></pre>
<p>And on Windows 7:</p>
<pre class="sourceCode"><code>&gt; runghc getaddr.hs
Local Area Connection
  IPv4: 192.168.0.107
  IPv6: fe80:0:0:0:ef54:7861:7df:6b7c
  MAC:  00:26:c9:e1:87:8c
VirtualBox Host-Only Network
  IPv4: 192.168.56.1
  IPv6: fe80:0:0:0:14b4:b3af:557:ad4a
  MAC:  08:00:27:00:d8:2a
Loopback Pseudo-Interface 1
  IPv4: 127.0.0.1
  IPv6: 0:0:0:0:0:0:0:1
  MAC:  00:00:00:00:00:00
... snipped out some garbage network interfaces
</code></pre>
<p>You’ll notice that the IPv6 addresses don’t have fully collapsed groups of zeros just yet, but they are still valid addresses.</p>
<p>I’ve tested this on Ubuntu 10.04, Windows XP &amp; Windows 7. It won’t install on Mac OS X or BSD just yet because of restrictions in the cabal file. I need to check out how <a href="http://www.kernel.org/doc/man-pages/online/pages/man3/getifaddrs.3.html">getifaddrs</a> works on those systems so I know what to do in the FFI code.</p>]]></summary>
</entry>
<entry>
    <title>'Edit with Vim' on x64</title>
    <link href="http://jacob.stanley.io/2010/07/28/edit-with-vim-x64/" />
    <id>http://jacob.stanley.io/2010/07/28/edit-with-vim-x64/</id>
    <updated>2010-07-28T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I’ve been using the <a href="http://code.google.com/p/vim-win3264/">64-bit version of Vim</a> so that I could get the ‘Edit with Vim’ context menu in Windows Explorer. This was all fine and good except that I wanted to use something that requires vim to be compiled with +ruby. The vanilla x86 gVim72 installer you can get at <a href="http://www.vim.org/download.php">vim.org</a> is compiled with +ruby, but it doesn’t have the explorer context menu on a 64-bit computer :(</p>
<p>The solution was to install the x86 vim from vim.org, then take the gvimext.dll from the 64-bit vim, and apply the following registry tweaks.</p>
<pre class="sourceCode"><code>Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Vim\Gvim]
&quot;path&quot;=&quot;C:\\Program Files (x86)\\Vim\\vim72\\gvim.exe&quot;

[HKEY_CLASSES_ROOT\CLSID\{51EEE242-AD87-11d3-9C1E-0090278BBD99}]
@=&quot;Vim Shell Extension&quot;

[HKEY_CLASSES_ROOT\CLSID\{51EEE242-AD87-11d3-9C1E-0090278BBD99}\InProcServer32]
@=&quot;C:\\Program Files (x86)\\Vim\\vim72\\gvimext64.dll&quot;
&quot;ThreadingModel&quot;=&quot;Apartment&quot;
</code></pre>
<p>To save anyone else the hassle of getting the bits you need from the 64-bit vim, I’ve zipped up everything you need (<a href="/files/gvimext64.zip">gvimext64.zip</a>). Just extract it to <code>C:\Program Files (x86)\Vim\vim72</code> and run the <code>gvimext64.reg</code> file.</p>]]></summary>
</entry>
<entry>
    <title>GitHub Haskell colours for GeSHi</title>
    <link href="http://jacob.stanley.io/2010/05/21/github-haskell-colours-for-geshi/" />
    <id>http://jacob.stanley.io/2010/05/21/github-haskell-colours-for-geshi/</id>
    <updated>2010-05-21T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p><em>This article is out of date, I don’t use Wordpress or GeSHi anymore for my blog</em></p>
<p><a href="http://qbnz.com/highlighter/">GeSHi</a> is the php-based syntax highlighter that I use for this blog. The Haskell highlighting included with GeSHi is a bit below par compared to say <a href="http://github.com/jystic/lambdasim/blob/master/Main.hs">GitHub</a>, which uses <a href="http://pygments.org/">pygments</a> for highlighting.</p>
<p>Not to be outdone, I though I’d delve in to GeSHi’s regular expression features to see if I could improve upon the default. I struggled a bit with things getting highlighted that had already been processed and matched to an alternate regular expression until I dug in to the GeSHi source to and found out how it escapes potential highlights. This led to some lovely regex like the one below as I attempted to work around things like <code>&lt;PIPE&gt;</code>, <code>&lt;SEMI&gt;</code> and other magical GeSHi escapes like <code>&lt;|!REG3XP1!&gt;</code>.</p>
<pre class="sourceCode"><code class="sourceCode perl"><span class="kw">/</span><span class="ot">&lt;</span><span class="ch">[</span><span class="bn">A-Z</span><span class="ch">]+</span><span class="ot">&gt;</span><span class="ch">|</span><span class="ot">&lt;\|!REG3XP</span><span class="bn">\d</span><span class="ch">*</span><span class="ot">!&gt;.</span><span class="ch">*?</span><span class="ot">\|&gt;</span><span class="kw">/</span></code></pre>
<p>One I figured this out things got a lot easier and I was able to get to a point that I’m pretty happy with. The symbol highlighting is still a bit hacky and I’d like to get to a point where all non-alphanumeric character groups are highlighted as symbols. For now though I’ve just added a few more (<code>&lt;$&gt;</code>, <code>&lt;|&gt;</code>, etc) to the hardcoded list that comes with GeSHi out of the box. So without any further ado, here are the results.</p>
<p>Before:</p>
<div class="figure">
<img src="/img/geshi-haskell-original.png" title="Original Colours" /><p class="caption"></p>
</div>
<p>After:</p>
<div class="figure">
<img src="/img/geshi-haskell-github.png" title="GitHub Colours" /><p class="caption"></p>
</div>
<p>You can download my modifications to the Haskell syntax file for GeSHi <a href="/files/haskell.php">here</a>. If I get some more time I’ll probably submit it back to the GeSHi project as a replacement or an alternative for Haskell.</p>
<p>One thing to note is that I’ve stripped out the url linking of Prelude functions. I felt that it wasn’t really that useful as I rarely want to know the details of those functions, it’s all the other ones that I want to know about! I toyed with the idea of linking functions and types to <a href="http://www.haskell.org/hoogle/">Hoogle</a> or <a href="http://holumbus.fh-wedel.de/hayoo/hayoo.html">Hayoo!</a> that might be worthwhile in the future.</p>
<p><strong>Download <a href="/files/haskell.php">haskell.php</a></strong></p>
<p><em>The syntax file above was built and tested on GeSHi 1.0.8.7, it will probably work on other versions, but you never know :)</em></p>]]></summary>
</entry>
<entry>
    <title>The Skyline Problem</title>
    <link href="http://jacob.stanley.io/2010/05/16/the-skyline-problem/" />
    <id>http://jacob.stanley.io/2010/05/16/the-skyline-problem/</id>
    <updated>2010-05-16T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>One of my friends recently had a job interview where he was asked to complete <a href="http://online-judge.uva.es/p/v1/105.html">The Skyline Problem</a>. It sounded interesting so I thought I’d see if my Haskell skills were up to the task.</p>
<img src="/img/skyline-problem.gif" alt="The Skyline Problem" width="600" />
<p>My first attempt took me a few hours to come up with. It’s been a little while since I’ve played with Haskell so a lot of time was spent fighting with the type checker. Eventually though I produced a solution that solved the problem. It works by exploding each building in to a set of discrete points, where a building <code>(1,11,3)</code> becomes the coordinates <code>[(1,11),(2,11),(3,11)]</code>. The points are then sorted and various filters are run across the data until we get the answer.</p>
<pre class="sourceCode"><code class="sourceCode haskell"><span class="kw">import</span> <span class="dt">Data.List</span><br /><br />main <span class="fu">=</span><br />  <span class="fu">putStrLn</span> <span class="fu">$</span><br />  <span class="fu">unwords</span> <span class="fu">$</span> <br />  <span class="fu">concatMap</span> (<span class="fu">map</span> <span class="fu">show</span> <span class="fu">.</span> list <span class="fu">.</span> <span class="fu">head</span>) <span class="fu">$</span><br />  groupBy' <span class="fu">snd</span> <span class="fu">$</span><br />  <span class="fu">map</span> <span class="fu">last</span> <span class="fu">$</span><br />  groupBy' <span class="fu">fst</span> <span class="fu">$</span><br />  <span class="fu">sort</span> <span class="fu">$</span><br />  <span class="fu">concatMap</span> explode buildings<br /><br />list (x,y) <span class="fu">=</span> [x,y]<br />groupBy' f <span class="fu">=</span> groupBy (\x y <span class="ot">-&gt;</span> f x <span class="fu">==</span> f y)<br />explode (l,h,r) <span class="fu">=</span> [(x,h) <span class="fu">|</span> x <span class="ot">&lt;-</span> [l<span class="fu">..</span>r<span class="fu">-</span><span class="dv">1</span>]] <span class="fu">++</span> [(r,<span class="dv">0</span>)]<br /><br />buildings <span class="fu">=</span> [(<span class="dv">1</span>,<span class="dv">11</span>,<span class="dv">5</span>),(<span class="dv">2</span>,<span class="dv">6</span>,<span class="dv">7</span>),(<span class="dv">3</span>,<span class="dv">13</span>,<span class="dv">9</span>),(<span class="dv">12</span>,<span class="dv">7</span>,<span class="dv">16</span>),<br />             (<span class="dv">14</span>,<span class="dv">3</span>,<span class="dv">25</span>),(<span class="dv">19</span>,<span class="dv">18</span>,<span class="dv">22</span>),(<span class="dv">23</span>,<span class="dv">13</span>,<span class="dv">29</span>),(<span class="dv">24</span>,<span class="dv">4</span>,<span class="dv">28</span>)]</code></pre>
<p>This seemed like it wasn’t the most efficient way to do things and I wasn’t reading my data from an input file yet. So, after a bit more thinking (and some <a href="http://stackoverflow.com/questions/1066234/the-skyline-problem">cheating</a>) I got some ideas on how to implement the program coming from a different angle. At some point I also wanted to try a golf solution (using as few characters as possible) so I stuck to using only the <code>Prelude</code>.</p>
<p>The revised solution works by scanning each building for every x-coordinate (1 - 9999) and calculating the height at that coordinate. The output is built by showing the current coordinates every time the maximum height changes. The thing I like about the revised solution is that it is basically just restating the problem in Haskell. I’ve included the type signatures below for completeness, but as always, they’re not required.</p>
<pre class="sourceCode"><code class="sourceCode haskell"><span class="ot">main </span><span class="ot">::</span> <span class="dt">IO</span> ()<br />main <span class="fu">=</span> <span class="fu">interact</span> <span class="fu">$</span> showSkyline <span class="fu">.</span> skyline <span class="fu">.</span> readBuildings<br /><br /><span class="ot">readBuildings </span><span class="ot">::</span> <span class="dt">String</span> <span class="ot">-&gt;</span> [[<span class="dt">Int</span>]]<br />readBuildings <span class="fu">=</span> <span class="fu">map</span> (<span class="fu">map</span> <span class="fu">read</span> <span class="fu">.</span> <span class="fu">words</span>) <span class="fu">.</span> <span class="fu">lines</span><br /><br /><span class="ot">skyline </span><span class="ot">::</span> [[<span class="dt">Int</span>]] <span class="ot">-&gt;</span> [(<span class="dt">Int</span>,<span class="dt">Int</span>)]<br />skyline buildings <span class="fu">=</span> [(x, height x) <span class="fu">|</span> x <span class="ot">&lt;-</span> [<span class="dv">1</span><span class="fu">..</span><span class="dv">9999</span>], isDiff x]<br />  <span class="kw">where</span> isDiff  x <span class="fu">=</span> height x <span class="fu">/=</span> height (x <span class="fu">-</span> <span class="dv">1</span>)<br />        height    <span class="fu">=</span> <span class="fu">maximum</span> <span class="fu">.</span> heights<br />        heights x <span class="fu">=</span> <span class="dv">0</span> <span class="fu">:</span> [h <span class="fu">|</span> [s,h,e] <span class="ot">&lt;-</span> buildings, s <span class="fu">&lt;=</span> x, x <span class="fu">&lt;</span> e]<br /><br /><span class="ot">showSkyline </span><span class="ot">::</span> [(<span class="dt">Int</span>,<span class="dt">Int</span>)] <span class="ot">-&gt;</span> <span class="dt">String</span><br />showSkyline <span class="fu">=</span> <span class="fu">unwords</span> <span class="fu">.</span> (<span class="fu">map</span> showPoint)<br /><br /><span class="ot">showPoint </span><span class="ot">::</span> (<span class="dt">Int</span>,<span class="dt">Int</span>) <span class="ot">-&gt;</span> <span class="dt">String</span><br />showPoint (x, y) <span class="fu">=</span> <span class="fu">show</span> x <span class="fu">++</span> <span class="st">&quot; &quot;</span> <span class="fu">++</span> <span class="fu">show</span> y</code></pre>
<p>Finally, I reduced the above solution to as few characters as possible so I could write an answer for the <a href="http://stackoverflow.com/questions/1066234/the-skyline-problem">Stack Overflow</a> code golf question.</p>
<p>It turned out to be 149 characters, which I was pretty happy with. I could have shaved off four more by inlining ‘b’, but that made the program take a lot longer to execute when using runghc for some reason. I’m not sure if it would have made a difference if I compiled it.</p>
<pre class="sourceCode"><code class="sourceCode haskell">main<span class="fu">=</span><span class="fu">interact</span> f<br />f i<span class="fu">=</span><span class="fu">unwords</span>[<span class="fu">show</span> x<span class="fu">++</span><span class="st">&quot; &quot;</span><span class="fu">++</span><span class="fu">show</span>(h x)<span class="fu">|</span>x<span class="ot">&lt;-</span>[<span class="dv">1</span><span class="fu">..</span><span class="dv">9999</span>],h x<span class="fu">/=</span>h(x<span class="fu">-</span><span class="dv">1</span>)] <span class="kw">where</span><br /> h x<span class="fu">=</span>maximum<span class="fu">$</span><span class="dv">0</span><span class="fu">:</span>[y<span class="fu">|</span>[l,y,r]<span class="ot">&lt;-</span>b,l<span class="fu">&lt;=</span>x,x<span class="fu">&lt;</span>r]<br /> b<span class="fu">=</span><span class="fu">map</span>(<span class="fu">map</span> <span class="fu">read</span><span class="fu">.</span><span class="fu">words</span>)<span class="fu">$</span>lines i</code></pre>
<p>If you discount reading the input or writing the output in a particular format, then it can be trimmed down to 75 characters. The input, stored in ‘b’, is the ‘buildings’ list from the first solution.</p>
<pre class="sourceCode"><code class="sourceCode haskell">h x<span class="fu">=</span>maximum<span class="fu">$</span><span class="dv">0</span><span class="fu">:</span>[y<span class="fu">|</span>(l,y,r)<span class="ot">&lt;-</span>b,l<span class="fu">&lt;=</span>x,x<span class="fu">&lt;</span>r]<br /><span class="fu">print</span>[(x,h x)<span class="fu">|</span>x<span class="ot">&lt;-</span>[<span class="dv">1</span><span class="fu">..</span><span class="dv">9999</span>],h x<span class="fu">/=</span>h(x<span class="fu">-</span><span class="dv">1</span>)]</code></pre>]]></summary>
</entry>
<entry>
    <title>Code Bubbles</title>
    <link href="http://jacob.stanley.io/2010/04/05/code-bubbles/" />
    <id>http://jacob.stanley.io/2010/04/05/code-bubbles/</id>
    <updated>2010-04-05T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Today I came across a really cool UI concept for an IDE called Code Bubbles. You can check out the video <a href="http://www.cs.brown.edu/people/acb/codebubbles_site.htm">here</a>.</p>
<p>I love the idea of having a massive workspace and being able to see relevant functions side by side. It was also really cool how you can email workspaces around with annotations.</p>]]></summary>
</entry>
<entry>
    <title>#haskell is awesome!</title>
    <link href="http://jacob.stanley.io/2009/10/23/the-haskell-channel-is-awesome/" />
    <id>http://jacob.stanley.io/2009/10/23/the-haskell-channel-is-awesome/</id>
    <updated>2009-10-23T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I was trying to follow along with a <a href="http://softwaresimply.blogspot.com/2009/04/basic-happstack-blog-app.html">few</a> <a href="http://tutorial.happstack.com">different</a> happstack tutorials and I found that I needed to cabal install a few things. Unfortunately when I did <code>cabal install happs-tutorial</code> I got the following:</p>
<pre class="sourceCode"><code>Happstack/Helpers/DirBrowse.hs:88:105:
    Couldn't match expected type `String' against inferred type `Bool'
    In the third argument of `hscolour', namely `False'
    In the second argument of `(.)', namely
        `(hscolour defaultColourPrefs False False f)'
    In the first argument of `($)', namely
        `BrowseHtmlString . (hscolour defaultColourPrefs False False f)'
cabal: Error: some packages failed to install:
happs-tutorial-0.9.0 depends on happstack-helpers-0.30 which failed to
install.
happstack-helpers-0.30 failed during the building phase. The exception was:
exit: ExitFailure 1
</code></pre>
<p>It turns out that happstack-helpers is listed as dependening on <code>hscolour &gt;= 1.0 &amp;&amp; &lt; 2.0</code> when in reality it fails to compile against v1.15 of hscolour. I was thinking, damn, I’m going to have to manually download the sources for happstack-helpers, edit the cabal file so it has the right references and compile it manually. That’s horribly convoluted for something that must happen all the time, there must be a better way!</p>
<p>I’ve been sitting on <a href="http://www.haskell.org/haskellwiki/IRC_channel">#haskell</a> recently so I asked the question, and got some very speedy responses:</p>
<pre class="sourceCode"><code>cabal install happs-tutorial --constraint=&quot;hscolor == 1.14&quot;
</code></pre>
<p>That did the trick, and with a lot less effort!</p>
<p>I’ve asked quite a few questions on #haskell in the last few days and the response has been almost immediate every time and I’ve had my problem solved within minutes. Granted I’m still a Haskell newbie so my questions are probably trivial, but even still, it puts to shame the support I’ve received from a lot of commercial companies.</p>]]></summary>
</entry>
<entry>
    <title>Happstack win!</title>
    <link href="http://jacob.stanley.io/2009/10/21/happstack-win/" />
    <id>http://jacob.stanley.io/2009/10/21/happstack-win/</id>
    <updated>2009-10-21T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Hackage finally came back up, but I ran in to trouble with some guy called <code>trhsx</code>. Every time I tried to <code>cabal install happstack</code> I got the following error:</p>
<pre class="sourceCode"><code>Configuring hsp-0.4.5...
Preprocessing library hsp-0.4.5...
Building hsp-0.4.5...
ghc: could not execute: trhsx
cabal: Error: some packages failed to install:
happstack-0.3.2 depends on hsp-0.4.5 which failed to install.
hsp-0.4.5 failed during the building phase. The exception was:
exit: ExitFailure 1
</code></pre>
<p>After some digging I found out that I was supposed to have <code>~/.cabal/bin</code> in my path, who would have thought? Anyway, I added the following to my <code>.bashrc</code>:</p>
<pre class="sourceCode"><code class="sourceCode bash"><span class="ot">PATH=$PATH</span>:~/.cabal/bin</code></pre>
<p>…and happstack installed without a hitch.</p>
<p>Win!</p>]]></summary>
</entry>
<entry>
    <title>Hackage is down :(</title>
    <link href="http://jacob.stanley.io/2009/10/19/hackage-is-down/" />
    <id>http://jacob.stanley.io/2009/10/19/hackage-is-down/</id>
    <updated>2009-10-19T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Tonight I decided it was time to sink my teeth in to <a href="http://happstack.com">Happstack</a>, the Haskell application server stack. I’m very keen to see how well Haskell handles web based applications and I really like the ideas behind Happstack.State. Unfortunately it looks like I may have picked the worst time of all as <a href="http://hackage.haskell.org">Hackage</a> seems to be down, so no “cabal install” for me!</p>
<p>Lets see how I go getting the dependencies by hand…</p>]]></summary>
</entry>
<entry>
    <title>What's with NullReferenceExceptions anyway?</title>
    <link href="http://jacob.stanley.io/2009/09/08/whats-with-nullreferenceexceptions-anyway/" />
    <id>http://jacob.stanley.io/2009/09/08/whats-with-nullreferenceexceptions-anyway/</id>
    <updated>2009-09-08T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Tony Hoare recently gave a talk at QCon about what he calls his <a href="http://qconlondon.com/london-2009/presentation/Null+References:+The+Billion+Dollar+Mistake">billion dollar mistake</a>, null references. It certainly rings true for me - not knowing whether a value can be null or not has been quite a major source of frustration for me. Conversely, checking for null when a method can never or should never return null is horrible as well, it bloats the code and distracts from the intent of the method.</p>
<p>ReSharper has some useful attributes that can be used to mitigate this somewhat. <code>NotNullAttribute</code> and <code>CanBeNullAttribute</code> give the ReSharper engine some hints that it can use to warn developers about potential mistakes, but at the end of the day you still end up with a boilerplate mess of if statements:</p>
<pre class="sourceCode"><code class="sourceCode cs">Apple apple = <span class="fu">PickApple</span>();<br /><br /><span class="kw">if</span> (apple == <span class="kw">null</span>)<br />{<br />    <span class="kw">return</span> <span class="kw">null</span>;<br />}<br /><br />Orange orange = <span class="fu">PickOrange</span>();<br /><br /><span class="kw">if</span> (orange == <span class="kw">null</span>)<br />{<br />    <span class="kw">return</span> <span class="kw">null</span>;<br />}<br /><br />FruitSalad fruitSalad = <span class="fu">MakeFruitSalad</span>(apple, orange);<br /><br /><span class="kw">if</span> (fruitSalad == <span class="kw">null</span>)<br />{<br />    <span class="kw">return</span> <span class="kw">null</span>;<br />}<br /><br /><span class="kw">return</span> <span class="fu">PackageForSale</span>(fruitSalad);</code></pre>
<p>Or perhaps even worse, the lovely arrow-head pattern. Reaching for the far edge of the screen with every possible null:</p>
<pre class="sourceCode"><code class="sourceCode cs">Apple apple = <span class="fu">PickApple</span>();<br /><br /><span class="kw">if</span> (apple != <span class="kw">null</span>)<br />{<br />    Orange orange = <span class="fu">PickOrange</span>();<br /><br />    <span class="kw">if</span> (orange != <span class="kw">null</span>)<br />    {<br />        FruitSalad fruitSalad = <span class="fu">MakeFruitSalad</span>(apple, orange);<br /><br />        <span class="kw">if</span> (fruitSalad != <span class="kw">null</span>)<br />        {<br />            <span class="kw">return</span> <span class="fu">PackageForSale</span>(fruitSalad);<br />        }<br />    }<br />}</code></pre>
<p>A solution to this problem that I’ve been using recently is straight out of the Haskell playbook, the Maybe monad. This simple tool wraps up the concept of uncertainty so that it is composable. This allows you to rewrite the above code like this using LINQ:</p>
<pre class="sourceCode"><code class="sourceCode cs"><span class="kw">return</span> from apple <span class="kw">in</span> <span class="fu">PickApple</span>()<br />       from orange <span class="kw">in</span> <span class="fu">PickOrange</span>()<br />       from fruitSalad <span class="kw">in</span> <span class="fu">MakeFruitSalad</span>(apple, orange)<br />       select <span class="fu">PackageForSale</span>(fruitSalad);</code></pre>
<p>Sweet! So it’s just like an <code>IEnumerable&lt;T&gt;</code> that is either empty, or contains a single value. So how does it work? Lets look at the type signature for <code>PickApple</code>:</p>
<pre class="sourceCode"><code class="sourceCode cs">Maybe&lt;Apple&gt; <span class="fu">PickApple</span>()</code></pre>
<p>Instead of returning an <code>Apple</code> directly, we return <code>Maybe&lt;Apple&gt;</code> (I like to pronounce this “maybe an apple”). This gives us two advantages. Firstly, it captures in the type system that we might not return a value. Secondly, it allows us to define a raft of common functions for working with <code>Maybe&lt;T&gt;</code> values.</p>
<p>So what does <code>Maybe&lt;T&gt;</code> look like? Here are the basics:</p>
<pre class="sourceCode"><code class="sourceCode cs"><span class="kw">public</span> <span class="kw">struct</span> Maybe&lt;T&gt;<br />{<br />    <span class="kw">private</span> <span class="kw">readonly</span> <span class="dt">bool</span> m_HasValue;<br />    <span class="kw">private</span> <span class="kw">readonly</span> T m_Value;<br /><br />    <span class="kw">public</span> <span class="fu">Maybe</span>(T value)<br />    {<br />        m_Value = value;<br />        m_HasValue = value != <span class="kw">null</span>;<br />    }<br /><br />    <span class="kw">public</span> T Value<br />    {<br />        get<br />        {<br />            <span class="kw">return</span> m_Value;<br />        }<br />    }<br /><br />    <span class="kw">public</span> <span class="dt">bool</span> HasValue<br />    {<br />        get<br />        {<br />            <span class="kw">return</span> m_HasValue;<br />        }<br />    }<br /><br />    <span class="kw">public</span> <span class="dt">bool</span> HasNothing<br />    {<br />        get<br />        {<br />            <span class="kw">return</span> !m_HasValue;<br />        }<br />    }<br /><br />    <span class="kw">public</span> <span class="kw">static</span> <span class="kw">implicit</span> <span class="kw">operator</span> Maybe&lt;T&gt;(T value)<br />    {<br />        <span class="kw">return</span> <span class="kw">new</span> Maybe&lt;T&gt;(value);<br />    }<br /><br />    <span class="kw">public</span> <span class="kw">static</span> Maybe&lt;T&gt; Nothing<br />    {<br />        get<br />        {<br />            <span class="kw">return</span> <span class="kw">default</span>(Maybe&lt;T&gt;);<br />        }<br />    }<br />}</code></pre>
<p>It’s important to note that <code>Maybe&lt;T&gt;</code> is a struct. If it was a class then <code>Maybe</code> could be null, nothing or contain a value. So you’d need to check for three possible cases and we wouldn’t have gained much at all!</p>
<p>So far this is looking pretty similar to <a href="http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx">Nullable<T></a> from the BCL. Unfortunately we can’t use <code>Nullable&lt;T&gt;</code> because it constrains <code>T</code> to structs only. This does bother me too much, I think <code>Maybe&lt;T&gt;</code> is a better name anyway.</p>
<p>So how do we do the funky LINQ stuff? We have to define what’s called the bind operator in functional languages. It describes how we can chain one maybe on to the next, and what to do if we encounter a maybe which has nothing in it. Unfortunately, because LINQ was designed to have a familiar SQL feel to it, this bind operation needs to be an extension method called <code>SelectMany</code>. This enables C# and Visual Basic to make use of it with the LINQ syntax.</p>
<p>So this is what “bind” looks like for our Maybe monad:</p>
<pre class="sourceCode"><code class="sourceCode cs"><span class="kw">public</span> <span class="kw">static</span> Maybe&lt;B&gt; SelectMany&lt;A, B&gt;(<span class="kw">this</span> Maybe&lt;A&gt; maybeA, Func&lt;A, Maybe&lt;B&gt;&gt; aToMaybeB)<br />{<br />    <span class="kw">if</span> (maybeA.<span class="fu">HasNothing</span>)<br />    {<br />        <span class="kw">return</span> Maybe&lt;B&gt;.<span class="fu">Nothing</span>;<br />    }<br /><br />    <span class="kw">return</span> <span class="fu">aToMaybeB</span>(maybeA.<span class="fu">Value</span>);<br />}</code></pre>
<p>It’s nothing special, it takes maybe an <code>A</code> and a function which goes from an <code>A</code> to maybe a <code>B.</code> The important thing here is that if A doesn’t have a value then the function <code>aToMaybeB</code> isn’t called. We’re still missing a small piece of the puzzle, but we’re able to write our original function as this:</p>
<pre class="sourceCode"><code class="sourceCode cs"><span class="kw">return</span> <span class="fu">PickApple</span>().<span class="fu">SelectMany</span>(apple =&gt;<br />       <span class="fu">PickOrange</span>().<span class="fu">SelectMany</span>(orange =&gt;<br />       <span class="fu">MakeFruitSalad</span>(apple, orange).<span class="fu">SelectMany</span>(fruitSalad =&gt;<br />       <span class="fu">PackageForSale</span>(fruitSalad))));</code></pre>
<p>The query syntax does work yet because LINQ requires one extra overload of <code>SelectMany.</code> This overload will describe how to chain two maybes together to yield a third. It’s purely an optimisation, so we’re not going to bother taking advantage of it in this case. We’ll just implement it in terms of our singular <code>SelectMany:</code></p>
<pre class="sourceCode"><code class="sourceCode cs"><span class="kw">public</span> <span class="kw">static</span> Maybe&lt;C&gt; SelectMany&lt;A, B, C&gt;(<span class="kw">this</span> Maybe&lt;A&gt; maybeA, Func&lt;A, Maybe&lt;B&gt;&gt; aToMaybeB, Func&lt;A, B, Maybe&lt;C&gt;&gt; abToMaybeC)<br />{<br />    <span class="kw">return</span> maybeA.<span class="fu">SelectMany</span>(a =&gt; <span class="fu">aToMaybeB</span>(a).<span class="fu">SelectMany</span>(b =&gt; <span class="fu">abToMaybeC</span>(a, b)));<br />}</code></pre>
<p>Ouch! That’s one scary looking method! You don’t need to worry too much about this guy. Unless you’re planning to do optimisations it’s exactly the same for every single monad. Having said that, you should see similarities between it and our usage of <code>SelectMany</code> in the previous example.</p>
<p>Once we have our “double bind” operation defined, the linq syntax should work as described earlier:</p>
<pre class="sourceCode"><code class="sourceCode cs"><span class="kw">return</span> from apple <span class="kw">in</span> <span class="fu">PickApple</span>()<br />       from orange <span class="kw">in</span> <span class="fu">PickOrange</span>()<br />       from fruitSalad <span class="kw">in</span> <span class="fu">MakeFruitSalad</span>(apple, orange)<br />       select <span class="fu">PackageForSale</span>(fruitSalad);</code></pre>
<p>Now that you have the basics you can add all sorts of extra functions for dealing with <code>Maybe&lt;T&gt;.</code> If I’m feeling keen I might post a follow up article on the additional functions that I’ve found useful. <code>OrNull</code> is a handy one for “unboxing” a <code>Maybe&lt;T&gt;</code> back to a naked value and <code>OrThrow</code> is another useful one which gets the inner value but throws if the <code>Maybe&lt;T&gt;</code> contains nothing.</p>
<p>So now you can say goodbye to <code>if (a != null)</code> right? Well, not quite, naked values always have the possibility of being null. It’s just an uncertainty that we’re going to have to deal with for the time being. However, if you always use <code>Maybe&lt;T&gt;</code> when a method might return “nothing” then you can fairly safely avoid checking for null when you’re working with values returned from your own code.</p>
<p>Hopefully we’ll be able to lock down naked values completely when we get code contracts in .NET 4.0. I’d love to see something which automatically annotates all arguments and return values with a contract ensuring that they can never be null.</p>
<p>A world without null, luxury!</p>]]></summary>
</entry>
<entry>
    <title>Jystic theme for Visual Studio</title>
    <link href="http://jacob.stanley.io/2009/08/02/jystic-theme-for-visual-studio/" />
    <id>http://jacob.stanley.io/2009/08/02/jystic-theme-for-visual-studio/</id>
    <updated>2009-08-02T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>When working with code I prefer to use themes with a dark background as I find they’re easier on the eyes. I love Rob Conery’s <a href="http://blog.wekeroad.com/blog/textmate-theme-for-visual-studio-take-2">TextMate Theme</a> and I’ve used it as a basis for my own theme.</p>
<p>The Jystic Theme uses a dark blue background and different colours for classes, interfaces, structs, delegates and enums. In addition to C# highlighting, it also supports xaml, aspx and css.</p>
<p>C#</p>
<a href="/img/jystic-theme-csharp.png"><img title="Jystic Theme C#"
src="/img/jystic-theme-csharp.png" alt="Jystic Theme C#" width="440"
/></a>
<p>XAML</p>
<a href="/img/jystic-theme-xaml.png"><img title="Jystic Theme Xaml"
src="/img/jystic-theme-xaml.png" alt="Jystic Theme Xaml" width="445"
/></a>
<p>ASPX</p>
<a href="/img/jystic-theme-aspx.png"><img title="Jystic Theme Aspx"
src="/img/jystic-theme-aspx.png" alt="Jystic Theme Aspx" width="419"
/></a>
<p>CSS</p>
<a href="/img/jystic-theme-css.png"><img title="Jystic Theme Css"
src="/img/jystic-theme-css.png" alt="Jystic Theme Css" width="386"
/></a>
<p><a title="Download Jystic Theme"
href="/files/jystic.vssettings">Download Jystic Theme</a></p>
<p>The font I like to use is DejaVu Sans Mono.</p>
<a href="/img/dejavu-sans-mono.png"><img class="alignnone size-full
wp-image-81" title="DejaVu Sans Mono" src="/img/dejavu-sans-mono.png"
alt="DejaVu Sans Mono" width="294" /></a>
<p><a href="http://dejavu-fonts.org/wiki/index.php?title=Download">Download DejaVu Sans Mono</a></p>]]></summary>
</entry>
<entry>
    <title>Design mode ViewModels with RhinoMocks</title>
    <link href="http://jacob.stanley.io/2009/06/06/design-mode-viewmodels-with-rhinomocks/" />
    <id>http://jacob.stanley.io/2009/06/06/design-mode-viewmodels-with-rhinomocks/</id>
    <updated>2009-06-06T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I’ve been having quite a lot of success lately with WPF thanks to an <a href="http://weblogs.asp.net/thomaslebrun/archive/2009/05/04/wpf-mvvm-how-to-get-data-in-design-time.aspx">awesome technique</a> that allows the injection of a dummy ViewModel at design time. This allows you to tweak the view in Visual Studio or Blend and see changes right away!</p>
<p>Unfortunately, having to add a property in so many places (the real ViewModel, the dummy ViewModel and the interface) was becoming a bit of a drag. So, I streamlined the process a bit by using RhinoMocks to generate the dummy ViewModel as a stub of the ViewModel interface:</p>
<pre class="sourceCode"><code class="sourceCode cs"><span class="kw">public</span> <span class="kw">class</span> SampleViewModel : ISampleViewModel<br />{<br />    <span class="co">// snip</span><br /><br />    <span class="kw">internal</span> <span class="kw">class</span> DesignModeFactory : IDesignModeFactory&lt;ISampleViewModel&gt;<br />    {<br />        <span class="kw">public</span> ISampleViewModel <span class="fu">CreateInstanceForDesignMode</span>()<br />        {<br />            <span class="dt">var</span> viewModel = MockRepository.<span class="fu">GenerateStub</span>&lt;ISampleViewModel&gt;();<br /><br />            viewModel.<span class="fu">Stub</span>(x =&gt; x.<span class="fu">Title</span>).<span class="fu">Return</span>(<span class="st">&quot;Design time title&quot;</span>);<br />            viewModel.<span class="fu">Text</span> = <span class="st">&quot;Design time text&quot;</span>;<br /><br />            <span class="kw">return</span> viewModel;<br />        }<br />    }<br />}<br /><br /><span class="kw">public</span> <span class="kw">interface</span> ISampleViewModel<br />{<br />    <span class="dt">string</span> Title<br />    {<br />        <span class="kw">get</span>;<br />    }<br /><br />    <span class="dt">string</span> Text<br />    {<br />        <span class="kw">get</span>;<br />        <span class="kw">set</span>;<br />    }<br />}</code></pre>
<p>I really like this approach because it guarantees that everything I’m binding to in design mode is available on the interface. This is important to note, because WPF uses reflection for binding, so I would have been allowed to bind to properties not on the interface and I wouldn’t realise until runtime.</p>
<p>So, all that’s left now is to hook up the dummy ViewModel. It would probably be best to do this with an attached property, but for me there was a more pragmatic solution. All of my views already derive from a specialised UserControl, which has a strongly typed ViewModel property for use by IoC containers. Given this arrangement, it was more pratical for me to add the dummy as part of the existing system.</p>
<pre class="sourceCode"><code class="sourceCode cs"><span class="kw">public</span> <span class="kw">class</span> UserControlView&lt;TViewModel&gt; : UserControl<br />{<br />    <span class="kw">public</span> TViewModel ViewModel<br />    {<br />        get<br />        {<br />            <span class="kw">return</span> (TViewModel)DataContext;<br />        }<br />        set<br />        {<br />            DataContext = value;<br />        }<br />    }<br /><br />    <span class="kw">public</span> <span class="fu">UserControlView</span>()<br />    {<br />        <span class="kw">if</span> (DesignerProperties.<span class="fu">GetIsInDesignMode</span>(<span class="kw">this</span>))<br />        {<br />            ViewModel = <span class="fu">CreateDesignModeViewModel</span>();<br />        }<br />    }<br /><br />    <span class="kw">private</span> <span class="kw">static</span> TViewModel <span class="fu">CreateDesignModeViewModel</span>()<br />    {<br />        IDesignModeFactory&lt;TViewModel&gt; factory = <span class="fu">ResolveFactory</span>();<br /><br />        <span class="kw">if</span> (factory == <span class="kw">null</span>)<br />        {<br />            <span class="kw">return</span> <span class="kw">default</span>(TViewModel);<br />        }<br /><br />        <span class="kw">return</span> factory.<span class="fu">CreateInstanceForDesignMode</span>();<br />    }<br /><br />    <span class="kw">private</span> <span class="kw">static</span> IDesignModeFactory&lt;TViewModel&gt; <span class="fu">ResolveFactory</span>()<br />    {<br />        <span class="kw">return</span> Resolve&lt;IDesignModeFactory&lt;TViewModel&gt;&gt;(<span class="kw">typeof</span>(TViewModel).<span class="fu">Assembly</span>);<br />    }<br /><br />    <span class="kw">private</span> <span class="kw">static</span> T Resolve&lt;T&gt;(Assembly assembly)<br />    {<br />        <span class="kw">return</span> assembly<br />            .<span class="fu">GetTypes</span>()<br />            .<span class="fu">Where</span>(x =&gt; <span class="kw">typeof</span>(T).<span class="fu">IsAssignableFrom</span>(x))<br />            .<span class="fu">Select</span>(x =&gt; (T)Activator.<span class="fu">CreateInstance</span>(x))<br />            .<span class="fu">FirstOrDefault</span>();<br />    }<br />}<br /><br /><span class="kw">public</span> <span class="kw">interface</span> IDesignModeFactory&lt;T&gt;<br />{<br />    T <span class="fu">CreateInstanceForDesignMode</span>();<br />}</code></pre>
<p>As you can see in the code above, we’re searching for the ViewModel’s DesignModeFactory. If we find one, we use it to create an instance of our dummy ViewModel. In my case, because I was already deriving from UserControlView, I don’t have to do anything extra! But, in case you haven’t used generics with xaml before, here’s the basic xaml for the view, the important part is the x:TypeArguments property.</p>
<pre class="sourceCode"><code class="sourceCode xml"><span class="kw">&lt;Sample:UserControlView</span><br /><span class="ot">    x:TypeArguments=</span><span class="st">&quot;Sample:ISampleViewModel&quot;</span><br /><span class="ot">    x:Class=</span><span class="st">&quot;Sample.SampleView&quot;</span><br /><span class="ot">    xmlns=</span><span class="st">&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;</span><br /><span class="ot">    xmlns:x=</span><span class="st">&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;</span><br /><span class="ot">    xmlns:Sample=</span><span class="st">&quot;clr-namespace:Sample&quot;</span><span class="kw">&gt;</span><br /><br />    <span class="co">&lt;!-- snip --&gt;</span><br /><br /><span class="kw">&lt;/Sample:UserControlView&gt;</span></code></pre>
<p>And there you have it, design mode support that’s a touch more <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a> :)</p>]]></summary>
</entry>
<entry>
    <title>Linq as a replacement for foreach</title>
    <link href="http://jacob.stanley.io/2009/05/31/linq-as-a-replacement-for-foreach/" />
    <id>http://jacob.stanley.io/2009/05/31/linq-as-a-replacement-for-foreach/</id>
    <updated>2009-05-31T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>The area of my code that has changed the most with the introduction of <a href="http://en.wikipedia.org/wiki/Language_Integrated_Query">linq</a> and <a href="http://en.wikipedia.org/wiki/Extension_method">extension methods</a> has to be the way that I treat standard collections. The number of times I used to write some code like this:</p>
<pre class="sourceCode"><code class="sourceCode cs">IEnumerable&lt;Fruit&gt; fruits = <span class="fu">GetAllTheFruit</span>();<br />List&lt;Fruit&gt; freshOnes = <span class="kw">new</span> List&lt;Fruit&gt;();<br /><br /><span class="kw">foreach</span> (Fruit fruit <span class="kw">in</span> fruits)<br />{<br />    <span class="kw">if</span> (fruit.<span class="fu">IsFresh</span>)<br />    {<br />        freshOnes.<span class="fu">Add</span>(fruit);<br />    }<br />}<br /><br /><span class="fu">MakeFruitSalad</span>(freshOnes);</code></pre>
<p>What a waste of time! The time it took to write all that boiler plate code, as well as the time for someone else to read and understand all that boiler plate code :( All we wanted was to get the fresh fruit, why is that so hard? Well, actually, with linq it’s pretty easy:</p>
<pre class="sourceCode"><code class="sourceCode cs">IEnumerable&lt;Fruit&gt; fruits = <span class="fu">GetAllTheFruit</span>();<br />IEnumerable&lt;Fruit&gt; freshOnes = fruits.<span class="fu">Where</span>(x =&gt; x.<span class="fu">IsFresh</span>);<br /><br /><span class="fu">MakeFruitSalad</span>(freshOnes);</code></pre>
<p>How about sorting?  I used to find myself doing something like this:</p>
<pre class="sourceCode"><code class="sourceCode cs">List&lt;Fruit&gt; sortedFruits = <span class="kw">new</span> List&lt;Fruit&gt;(<span class="fu">GetAllTheFruit</span>());<br />sortedFruits.<span class="fu">Sort</span>(<span class="kw">new</span> <span class="fu">FreshnessComparer</span>());<br /><br /><span class="kw">class</span> FreshnessComparer : IComparer&lt;Fruit&gt;<br />{<br />    <span class="kw">public</span> <span class="dt">int</span> <span class="fu">Compare</span>(Fruit x, Fruit y)<br />    {<br />        <span class="kw">return</span> x.<span class="fu">Freshness</span>.<span class="fu">CompareTo</span>(y.<span class="fu">Freshness</span>);<br />    }<br />}</code></pre>
<p>That’s great, but do I really need to make a new class/method just to sort by freshness? Not if I use linq:</p>
<pre class="sourceCode"><code class="sourceCode cs">IEnumerable&lt;Fruit&gt; sortedFruits =<br />    <span class="fu">GetAllTheFruit</span>().<span class="fu">OrderBy</span>(x =&gt; x.<span class="fu">Freshness</span>);</code></pre>
<p>What if I just want the single freshest fruit? I could do this:</p>
<pre class="sourceCode"><code class="sourceCode cs">Fruit freshest = <span class="kw">null</span>;<br /><br /><span class="kw">foreach</span> (Fruit fruit <span class="kw">in</span> sortedFruits)<br />{<br />    freshest = fruit;<br />    <span class="kw">break</span>;<br />}<br /><br /><span class="co">// got the freshest, or null if there</span><br /><span class="co">// was no fruit in 'sortedFruits'</span></code></pre>
<p>Or I can just use linq:</p>
<pre class="sourceCode"><code class="sourceCode cs">Fruit freshest = sortedFruits.<span class="fu">FirstOrDefault</span>();</code></pre>
<p>Great, so it’s nicer to use from the consumer’s point of view, but what about the provider’s? This is another area where I really like linq. Linq works on <code>IEnumerable&lt;T&gt;</code>, a really simple interface to implement when compared to the likes of <code>IList&lt;T&gt;</code> or <code>ICollection&lt;T&gt;</code>. It really allows our implementations to choose the best data structure for the job, instead of having to return an <code>IList&lt;T&gt;</code> or <code>ICollection&lt;T&gt;</code> just because they’ll be more convieniant for the consumer.</p>
<p>Linq is proof enough for me that object oriented and functional programming paradigms can complement each other nicely. Not having access to functional stuff like linq is one of my major pain points anytime I have to use Java these days.</p>]]></summary>
</entry>
<entry>
    <title>Hello World!</title>
    <link href="http://jacob.stanley.io/2009/05/20/hello-world/" />
    <id>http://jacob.stanley.io/2009/05/20/hello-world/</id>
    <updated>2009-05-20T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>So, here we are again, attempt number three at maintaining a blog. Let’s see if I can keep it up this time :)</p>
<p>I’ll be posting at least once a week, hopefully following Ayende’s method of posting about things I’m currently working on. I’ve moved my web hosting from a server in the US to an Australian server, and that’s sped up my response times to the site considerably. It makes a big difference to motivation when you’re not sitting around waiting for most of the time. Maybe I’m just impatient :P</p>
<p>Given this is a hello world post and I’m learning Haskell at the moment, I thought I’d try and craft one line of Haskell that does something interesting to come up with the classic <code>&quot;Hello World!&quot;</code>. Although, perhaps I should have tried to write a blog engine in one line of Haskell, it sure is terse enough :P</p>
<p>Here’s what I came up with:</p>
<table class="sourceCode"><tr><td class="nums" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2<br />3</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode haskell"><span class="fu">foldr</span> (\x y <span class="ot">-&gt;</span> x <span class="fu">++</span> <span class="st">&quot; &quot;</span> <span class="fu">++</span> y) <span class="st">&quot;!&quot;</span><br />  (<span class="fu">map</span> (\(x<span class="fu">:</span>xs) <span class="ot">-&gt;</span> <span class="fu">toUpper</span> x <span class="fu">:</span> <span class="fu">map</span> <span class="fu">toLower</span> xs)<br />       [<span class="st">&quot;HELLO&quot;</span>, <span class="st">&quot;WORLD&quot;</span>])</code></pre></td></tr></table>
<p>What does it do?</p>
<p>It creates a list containing the strings <code>&quot;HELLO&quot;</code> and <code>&quot;WORLD&quot;</code></p>
<p>It maps a lambda on to the list so that the first character of each string in the list is uppercase and the rest of the characters are lowercase (giving us <code>&quot;Hello&quot;</code>, <code>&quot;World&quot;</code>)</p>
<p>It does a fold right on the resulting list, with a lambda that concatenates each item in the list using a space as a separator and an exclamation mark as the intial seed</p>
<p>The result?</p>
<pre class="sourceCode"><code class="sourceCode haskell"><span class="st">&quot;Hello World !&quot;</span></code></pre>
<p>Ideally I’d have liked to not have the space in between <code>&quot;World&quot;</code> and <code>&quot;!&quot;</code>, but my haskell-fu isn’t good enough yet :)</p>]]></summary>
</entry>

</feed>

