<?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/"
	xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Paolo Capriotti</title>
	<atom:link href="http://pcapriotti.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://pcapriotti.wordpress.com</link>
	<description>KDE hacking and more</description>
	<lastBuildDate>Thu, 11 Jun 2009 16:09:23 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='pcapriotti.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/f200926c413a2de19b2592a93e8a7251?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>Paolo Capriotti</title>
		<link>http://pcapriotti.wordpress.com</link>
	</image>
			<item>
		<title>Monads for Markov chains</title>
		<link>http://pcapriotti.wordpress.com/2008/10/16/monads-for-markov-chains/</link>
		<comments>http://pcapriotti.wordpress.com/2008/10/16/monads-for-markov-chains/#comments</comments>
		<pubDate>Thu, 16 Oct 2008 13:11:06 +0000</pubDate>
		<dc:creator>pcapriotti</dc:creator>
				<category><![CDATA[haskell]]></category>
		<category><![CDATA[literate programming]]></category>
		<category><![CDATA[markov chains]]></category>
		<category><![CDATA[monads]]></category>

		<guid isPermaLink="false">http://pcapriotti.wordpress.com/?p=46</guid>
		<description><![CDATA[This is my first literate Haskell post, and actually my first post on Haskell, and my first attempt at literate programming. I spent (wasted?) a lot of time in trying to make the code segments render nicely on WordPress, with a process that was only partially automated and very tedious. I think I will cook [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pcapriotti.wordpress.com&blog=806312&post=46&subd=pcapriotti&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><em>This is my first literate Haskell post, and actually my first post on Haskell, and my first attempt at literate programming. I spent (wasted?) a lot of time in trying to make the code segments render nicely on WordPress, with a process that was only partially automated and very tedious. I think I will cook up some script to automate it completely, if I ever get to write another such post.</em></p>
<p>Suppose you need to model a finite <a href="http://en.wikipedia.org/wiki/Markov_chain">Markov chain</a> in code. There are essentially two ways of doing that: one is to simply run a simulation of the Markov chain using a random number generator to obtain dice rolls and random cards from the decks, the other is to create a <a href="http://en.wikipedia.org/wiki/Stochastic_matrix">stochastic matrix</a> containing the transition probabilities for each pair of states.</p>
<p>In this post I will show how a single monadic description of the Markov chain dynamics can be used to obtain both a simulator and the transition matrix.</p>
<pre style="font-size:140%;"><span style="font-style:italic;color:#408080;">&gt; {-# LANGUAGE MultiParamTypeClasses, </span>
<span style="font-style:italic;color:#408080;">&gt;     FlexibleInstances, </span>
<span style="font-style:italic;color:#408080;">&gt;     GeneralizedNewtypeDeriving #-}</span>
<span style="font-style:italic;color:#408080;">&gt;</span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="font-weight:bold;color:#008000;">import</span> <span style="font-weight:bold;color:#0000ff;">Control.Arrow</span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="font-weight:bold;color:#008000;">import</span> <span style="font-weight:bold;color:#0000ff;">Control.Monad</span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="font-weight:bold;color:#008000;">import</span> <span style="font-weight:bold;color:#0000ff;">Control.Monad.State.Strict</span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="font-weight:bold;color:#008000;">import</span> <span style="font-weight:bold;color:#0000ff;">Data.Array</span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="font-weight:bold;color:#008000;">import</span> <span style="font-weight:bold;color:#0000ff;">Random</span></pre>
<p>Let&#8217;s start with an example of Markov chain and how we would like to be able to implement in Haskell. Consider a simplified version of the familiar <a href="http://en.wikipedia.org/wiki/Monopoly_(game)">Monopoly</a> game: there are 40 squares (numbered 0 to 39), you throw two 6-sided dice each turn, some special squares have particular effects (see below), if you get a double roll three times in a row, you go to jail. The special squares are:</p>
<p>30: go to jail<br />
2, 17, 33: Community Chest<br />
7, 22, 36: Chance</p>
<p>Community Chest (CC) and Chance (CH) make you take a card from a deck and move to some other place depending on what&#8217;s written on the card. You will find the details on the code, so I won&#8217;t explain them here.</p>
<p>This is of course a Markov chain, where the states can be represented by:</p>
<pre style="font-size:140%;"><span style="font-style:italic;color:#408080;">&gt; </span><span style="font-weight:bold;color:#008000;">type</span> <span style="color:#b00040;">Square</span> <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="color:#b00040;">Int</span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="font-weight:bold;color:#008000;">data</span> <span style="color:#b00040;">GameState</span> <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="color:#b00040;">GS</span> {
<span style="font-style:italic;color:#408080;">&gt;       </span><span style="color:#0000ff;">position</span> <span style="font-weight:bold;color:#aa22ff;">::</span> <span style="color:#b00040;">Square</span>,
<span style="font-style:italic;color:#408080;">&gt;       </span><span style="color:#0000ff;">doubles</span> <span style="font-weight:bold;color:#aa22ff;">::</span> <span style="color:#b00040;">Int</span> } <span style="font-weight:bold;color:#008000;">deriving</span> (<span style="color:#b00040;">Eq</span>, <span style="color:#b00040;">Ord</span>, <span style="color:#b00040;">Show</span>)</pre>
<p>and a description of the game can be given in a monadic style like this:</p>
<pre style="font-size:140%;"><span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">sGO</span> <span style="font-weight:bold;color:#aa22ff;">::</span> <span style="color:#b00040;">Square</span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">sGO</span> <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="color:#666666;">0</span>
<span style="font-style:italic;color:#408080;">&gt; </span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">sJAIL</span> <span style="font-weight:bold;color:#aa22ff;">::</span> <span style="color:#b00040;">Square</span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">sJAIL</span> <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="color:#666666;">10</span>
<span style="font-style:italic;color:#408080;">&gt;</span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">finalize</span> <span style="font-weight:bold;color:#aa22ff;">::</span> <span style="color:#b00040;">Square</span> <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> <span style="color:#b00040;">Game</span> <span style="color:#b00040;">Square</span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">finalize</span> n
<span style="font-style:italic;color:#408080;">&gt;     </span><span style="color:#666666;">|</span> n <span style="color:#666666;">==</span> <span style="color:#666666;">2</span> <span style="color:#666666;">||</span> n <span style="color:#666666;">==</span> <span style="color:#666666;">17</span> <span style="color:#666666;">||</span> n <span style="color:#666666;">==</span> <span style="color:#666666;">33</span> <span style="font-weight:bold;color:#aa22ff;">=</span> cc n
<span style="font-style:italic;color:#408080;">&gt;     </span><span style="color:#666666;">|</span> n <span style="color:#666666;">==</span> <span style="color:#666666;">7</span> <span style="color:#666666;">||</span> n <span style="color:#666666;">==</span> <span style="color:#666666;">22</span> <span style="color:#666666;">||</span> n <span style="color:#666666;">==</span> <span style="color:#666666;">36</span> <span style="font-weight:bold;color:#aa22ff;">=</span> ch n
<span style="font-style:italic;color:#408080;">&gt;     </span><span style="color:#666666;">|</span> n <span style="color:#666666;">==</span> <span style="color:#666666;">30</span> <span style="font-weight:bold;color:#aa22ff;">=</span> return sJAIL
<span style="font-style:italic;color:#408080;">&gt;     </span><span style="color:#666666;">|</span> otherwise <span style="font-weight:bold;color:#aa22ff;">=</span> return n
<span style="font-style:italic;color:#408080;">&gt; </span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">cc</span> <span style="font-weight:bold;color:#aa22ff;">::</span> <span style="color:#b00040;">Square</span> <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> <span style="color:#b00040;">Game</span> <span style="color:#b00040;">Square</span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">cc</span> n <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="font-weight:bold;color:#008000;">do</span> i <span style="font-weight:bold;color:#aa22ff;">&lt;-</span> choose (<span style="color:#666666;">1</span> <span style="font-weight:bold;color:#aa22ff;">::</span> <span style="color:#b00040;">Int</span>, <span style="color:#666666;">16</span>)
<span style="font-style:italic;color:#408080;">&gt;           </span><span style="color:#0000ff;">return</span> <span style="color:#666666;">$</span> <span style="font-weight:bold;color:#008000;">case</span> i <span style="font-weight:bold;color:#008000;">of</span>
<span style="font-style:italic;color:#408080;">&gt;                      </span><span style="color:#666666;">1</span> <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> sGO
<span style="font-style:italic;color:#408080;">&gt;                      </span><span style="color:#666666;">2</span> <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> sJAIL
<span style="font-style:italic;color:#408080;">&gt;                      </span><span style="font-weight:bold;color:#008000;">_</span> <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> n
<span style="font-style:italic;color:#408080;">&gt; </span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">ch</span> <span style="font-weight:bold;color:#aa22ff;">::</span> <span style="color:#b00040;">Square</span> <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> <span style="color:#b00040;">Game</span> <span style="color:#b00040;">Square</span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">ch</span> n <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="font-weight:bold;color:#008000;">do</span> i <span style="font-weight:bold;color:#aa22ff;">&lt;-</span> choose (<span style="color:#666666;">1</span> <span style="font-weight:bold;color:#aa22ff;">::</span> <span style="color:#b00040;">Int</span>, <span style="color:#666666;">16</span>)
<span style="font-style:italic;color:#408080;">&gt;           </span><span style="color:#0000ff;">return</span> <span style="color:#666666;">$</span> <span style="font-weight:bold;color:#008000;">case</span> i <span style="font-weight:bold;color:#008000;">of</span>
<span style="font-style:italic;color:#408080;">&gt;                      </span><span style="color:#666666;">1</span> <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> sGO
<span style="font-style:italic;color:#408080;">&gt;                      </span><span style="color:#666666;">2</span> <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> sJAIL
<span style="font-style:italic;color:#408080;">&gt;                      </span><span style="color:#666666;">3</span> <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> <span style="color:#666666;">11</span>
<span style="font-style:italic;color:#408080;">&gt;                      </span><span style="color:#666666;">4</span> <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> <span style="color:#666666;">24</span>
<span style="font-style:italic;color:#408080;">&gt;                      </span><span style="color:#666666;">5</span> <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> <span style="color:#666666;">39</span>
<span style="font-style:italic;color:#408080;">&gt;                      </span><span style="color:#666666;">6</span> <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> <span style="color:#666666;">5</span>
<span style="font-style:italic;color:#408080;">&gt;                      </span><span style="color:#666666;">7</span> <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> nextR n
<span style="font-style:italic;color:#408080;">&gt;                      </span><span style="color:#666666;">8</span> <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> nextR n
<span style="font-style:italic;color:#408080;">&gt;                      </span><span style="color:#666666;">9</span> <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> nextU n
<span style="font-style:italic;color:#408080;">&gt;                      </span><span style="color:#666666;">10</span> <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> n <span style="color:#666666;">-</span> <span style="color:#666666;">3</span>
<span style="font-style:italic;color:#408080;">&gt;                      </span><span style="font-weight:bold;color:#008000;">_</span> <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> n
<span style="font-style:italic;color:#408080;">&gt;     </span><span style="font-weight:bold;color:#008000;">where</span>
<span style="font-style:italic;color:#408080;">&gt;       </span><span style="color:#0000ff;">nextR</span> n <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="font-weight:bold;color:#008000;">let</span> n' <span style="font-weight:bold;color:#aa22ff;">=</span> n <span style="color:#666666;">+</span> <span style="color:#666666;">5</span>
<span style="font-style:italic;color:#408080;">&gt;                 </span><span style="font-weight:bold;color:#008000;">in</span> n' <span style="color:#666666;">-</span> (n' `mod` <span style="color:#666666;">5</span>)
<span style="font-style:italic;color:#408080;">&gt;       </span><span style="color:#0000ff;">nextU</span> n
<span style="font-style:italic;color:#408080;">&gt;           </span><span style="color:#666666;">|</span> n <span style="color:#666666;">&gt;=</span> <span style="color:#666666;">12</span> <span style="color:#666666;">&amp;&amp;</span> n <span style="color:#666666;">&lt;</span> <span style="color:#666666;">28</span> <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="color:#666666;">28</span>
<span style="font-style:italic;color:#408080;">&gt;           </span><span style="color:#666666;">|</span> otherwise <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="color:#666666;">12</span>
<span style="font-style:italic;color:#408080;">&gt; </span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">roll</span> <span style="font-weight:bold;color:#aa22ff;">::</span> <span style="color:#b00040;">Game</span> (<span style="color:#b00040;">Int</span>, <span style="color:#b00040;">Int</span>)
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">roll</span> <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="font-weight:bold;color:#008000;">let</span> r1 <span style="font-weight:bold;color:#aa22ff;">=</span> choose (<span style="color:#666666;">1</span>, <span style="color:#666666;">6</span>)
<span style="font-style:italic;color:#408080;">&gt;        </span><span style="font-weight:bold;color:#008000;">in</span> liftM2 (,) r1 r1
<span style="font-style:italic;color:#408080;">&gt; </span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">markDouble</span> <span style="font-weight:bold;color:#aa22ff;">::</span> <span style="color:#b00040;">Bool</span> <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> <span style="color:#b00040;">Game</span> <span style="color:#008000;">()</span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">markDouble</span> <span style="color:#b00040;">True</span> <span style="font-weight:bold;color:#aa22ff;">=</span> modify <span style="color:#666666;">$</span> <span style="color:#0000ff;">\</span>s <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> s {
<span style="font-style:italic;color:#408080;">&gt;                     </span><span style="color:#0000ff;">doubles</span> <span style="font-weight:bold;color:#aa22ff;">=</span> doubles s <span style="color:#666666;">+</span> <span style="color:#666666;">1</span> }
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">markDouble</span> <span style="color:#b00040;">False</span> <span style="font-weight:bold;color:#aa22ff;">=</span> modify <span style="color:#666666;">$</span> <span style="color:#0000ff;">\</span>s <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> s {
<span style="font-style:italic;color:#408080;">&gt;                      </span><span style="color:#0000ff;">doubles</span> <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="color:#666666;">0</span>
<span style="font-style:italic;color:#408080;">&gt;                    </span>}
<span style="font-style:italic;color:#408080;">&gt;</span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">goTo</span> <span style="font-weight:bold;color:#aa22ff;">::</span> <span style="color:#b00040;">Square</span> <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> <span style="color:#b00040;">Game</span> <span style="color:#008000;">()</span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">goTo</span> n <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="font-weight:bold;color:#008000;">let</span> n' <span style="font-weight:bold;color:#aa22ff;">=</span> n `mod` <span style="color:#666666;">40</span>
<span style="font-style:italic;color:#408080;">&gt;          </span><span style="font-weight:bold;color:#008000;">in</span> modify <span style="color:#666666;">$</span> <span style="color:#0000ff;">\</span>s <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> s { position <span style="font-weight:bold;color:#aa22ff;">=</span> n' }
<span style="font-style:italic;color:#408080;">&gt; </span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">game</span> <span style="font-weight:bold;color:#aa22ff;">::</span> <span style="color:#b00040;">Game</span> <span style="color:#008000;">()</span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">game</span> <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="font-weight:bold;color:#008000;">do</span> n <span style="font-weight:bold;color:#aa22ff;">&lt;-</span> liftM position get
<span style="font-style:italic;color:#408080;">&gt;           </span>(a, b) <span style="font-weight:bold;color:#aa22ff;">&lt;-</span> roll
<span style="font-style:italic;color:#408080;">&gt;           </span><span style="color:#0000ff;">markDouble</span> (a <span style="color:#666666;">==</span> b)
<span style="font-style:italic;color:#408080;">&gt;           </span><span style="color:#0000ff;">d</span> <span style="font-weight:bold;color:#aa22ff;">&lt;-</span> liftM doubles get
<span style="font-style:italic;color:#408080;">&gt;           </span><span style="font-weight:bold;color:#008000;">if</span> d <span style="color:#666666;">==</span> <span style="color:#666666;">3</span>
<span style="font-style:italic;color:#408080;">&gt;            </span><span style="font-weight:bold;color:#008000;">then</span> <span style="font-weight:bold;color:#008000;">do</span> markDouble <span style="color:#b00040;">False</span>
<span style="font-style:italic;color:#408080;">&gt;                    </span><span style="color:#0000ff;">goTo</span> sJAIL
<span style="font-style:italic;color:#408080;">&gt;            </span><span style="font-weight:bold;color:#008000;">else</span> <span style="font-weight:bold;color:#008000;">do</span> <span style="font-weight:bold;color:#008000;">let</span> n' <span style="font-weight:bold;color:#aa22ff;">=</span> n <span style="color:#666666;">+</span> a <span style="color:#666666;">+</span> b
<span style="font-style:italic;color:#408080;">&gt;                    </span><span style="color:#0000ff;">n''</span> <span style="font-weight:bold;color:#aa22ff;">&lt;-</span> finalize n'
<span style="font-style:italic;color:#408080;">&gt;                    </span><span style="color:#0000ff;">goTo</span> n''
<span style="font-style:italic;color:#408080;">&gt; </span></pre>
<p>As you can see, <code>Game</code> is a state monad, with an additional function <code>choose</code> that gives us a random element of a range:</p>
<pre style="font-size:140%;"><span style="font-style:italic;color:#408080;">&gt; </span><span style="font-weight:bold;color:#008000;">class</span> <span style="color:#b00040;">MonadState</span> s m <span style="font-weight:bold;color:#aa22ff;">=&gt;</span> <span style="color:#b00040;">MonadMC</span> s m <span style="font-weight:bold;color:#008000;">where</span>
<span style="font-style:italic;color:#408080;">&gt;     </span><span style="color:#0000ff;">choose</span> <span style="font-weight:bold;color:#aa22ff;">::</span> (<span style="color:#b00040;">Enum</span> a) <span style="font-weight:bold;color:#aa22ff;">=&gt;</span> (a, a) <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> m a</pre>
<p>This can be implemented very easily using the (strict) state monad and a random generator:</p>
<pre style="font-size:140%;"><span style="font-style:italic;color:#408080;">&gt; </span><span style="font-weight:bold;color:#008000;">newtype</span> <span style="color:#b00040;">MCSim</span> s a <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="color:#b00040;">MCSim</span> (<span style="color:#b00040;">State</span> ([s], <span style="color:#b00040;">StdGen</span>) a)
<span style="font-style:italic;color:#408080;">&gt;     </span><span style="font-weight:bold;color:#008000;">deriving</span> <span style="color:#b00040;">Monad</span>
<span style="font-style:italic;color:#408080;">&gt; </span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="font-weight:bold;color:#008000;">instance</span> <span style="color:#b00040;">MonadState</span> s (<span style="color:#b00040;">MCSim</span> s) <span style="font-weight:bold;color:#008000;">where</span>
<span style="font-style:italic;color:#408080;">&gt;     </span><span style="color:#0000ff;">get</span> <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="color:#b00040;">MCSim</span> <span style="color:#666666;">$</span> liftM (head <span style="color:#666666;">.</span> fst) get
<span style="font-style:italic;color:#408080;">&gt;     </span><span style="color:#0000ff;">put</span> x <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="color:#b00040;">MCSim</span> <span style="color:#666666;">.</span> modify <span style="color:#666666;">$</span> <span style="color:#0000ff;">\</span>(xs, g) <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> (x <span style="color:#b00040;">:</span> xs, g)
<span style="font-style:italic;color:#408080;">&gt; </span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="font-weight:bold;color:#008000;">instance</span> <span style="color:#b00040;">MonadMC</span> s (<span style="color:#b00040;">MCSim</span> s) <span style="font-weight:bold;color:#008000;">where</span>
<span style="font-style:italic;color:#408080;">&gt;     </span><span style="color:#0000ff;">choose</span> (a, b) <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="color:#b00040;">MCSim</span> <span style="color:#666666;">$</span>
<span style="font-style:italic;color:#408080;">&gt;                     </span><span style="font-weight:bold;color:#008000;">do</span> (xs, g) <span style="font-weight:bold;color:#aa22ff;">&lt;-</span> get
<span style="font-style:italic;color:#408080;">&gt;                        </span><span style="font-weight:bold;color:#008000;">let</span> bnds <span style="font-weight:bold;color:#aa22ff;">=</span> (fromEnum a, fromEnum b)
<span style="font-style:italic;color:#408080;">&gt;                        </span><span style="font-weight:bold;color:#008000;">let</span> (y, g') <span style="font-weight:bold;color:#aa22ff;">=</span> randomR bnds g
<span style="font-style:italic;color:#408080;">&gt;                        </span><span style="color:#0000ff;">put</span> (xs, g')
<span style="font-style:italic;color:#408080;">&gt;                        </span><span style="color:#0000ff;">return</span> <span style="color:#666666;">.</span> toEnum <span style="color:#666666;">$</span> y
<span style="font-style:italic;color:#408080;">&gt; </span>
<span style="font-style:italic;color:#408080;">&gt; -- type Game a = MCSim GameState a</span>
<span style="font-style:italic;color:#408080;">&gt;</span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">runSim</span> <span style="font-weight:bold;color:#aa22ff;">::</span> <span style="color:#b00040;">StdGen</span> <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> <span style="color:#b00040;">Int</span> <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> s <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> <span style="color:#b00040;">MCSim</span> s <span style="color:#008000;">()</span> <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> [s]
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">runSim</span> g n start m <span style="font-weight:bold;color:#aa22ff;">=</span> fst <span style="color:#666666;">$</span> execState m' ([start], g)
<span style="font-style:italic;color:#408080;">&gt;     </span><span style="font-weight:bold;color:#008000;">where</span>
<span style="font-style:italic;color:#408080;">&gt;       </span>(<span style="color:#b00040;">MCSim</span> m') <span style="font-weight:bold;color:#aa22ff;">=</span> foldr (<span style="color:#666666;">&gt;&gt;</span>) (return <span style="color:#008000;">()</span>) <span style="color:#666666;">$</span> replicate n m</pre>
<p>The <code>runSim</code> function runs the simulation and returns the list of visited states.  This is already quite nice, but the best thing is that the <em>same</em> code can be used to create the transition matrix, just swapping in a new implementation of the <code>Game</code> type alias:</p>
<pre style="font-size:140%;"><span style="font-style:italic;color:#408080;">&gt; </span><span style="font-weight:bold;color:#008000;">newtype</span> <span style="color:#b00040;">MC</span> s a <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="color:#b00040;">MC</span> (s <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> [(s, <span style="color:#b00040;">Double</span>, a)])
<span style="font-style:italic;color:#408080;">&gt; </span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="font-weight:bold;color:#008000;">instance</span> <span style="color:#b00040;">Monad</span> (<span style="color:#b00040;">MC</span> s) <span style="font-weight:bold;color:#008000;">where</span>
<span style="font-style:italic;color:#408080;">&gt;     </span><span style="color:#0000ff;">return</span> x <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="color:#b00040;">MC</span> <span style="color:#666666;">$</span> <span style="color:#0000ff;">\</span>s <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> return (s, <span style="color:#666666;">1.0</span>, x)
<span style="font-style:italic;color:#408080;">&gt;     </span>(<span style="color:#b00040;">MC</span> m) <span style="color:#666666;">&gt;&gt;=</span> f <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="color:#b00040;">MC</span> <span style="color:#666666;">$</span> <span style="color:#0000ff;">\</span>s <span style="font-weight:bold;color:#aa22ff;">-&gt;</span>
<span style="font-style:italic;color:#408080;">&gt;                    </span><span style="font-weight:bold;color:#008000;">do</span> (s, p, x) <span style="font-weight:bold;color:#aa22ff;">&lt;-</span> m s
<span style="font-style:italic;color:#408080;">&gt;                       </span><span style="font-weight:bold;color:#008000;">let</span> (<span style="color:#b00040;">MC</span> m') <span style="font-weight:bold;color:#aa22ff;">=</span> f x
<span style="font-style:italic;color:#408080;">&gt;                       </span>(s', q, y) <span style="font-weight:bold;color:#aa22ff;">&lt;-</span> m' s
<span style="font-style:italic;color:#408080;">&gt;                       </span><span style="color:#0000ff;">return</span> (s', p <span style="color:#666666;">*</span> q, y)
<span style="font-style:italic;color:#408080;">&gt; </span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="font-weight:bold;color:#008000;">instance</span> <span style="color:#b00040;">MonadState</span> s (<span style="color:#b00040;">MC</span> s) <span style="font-weight:bold;color:#008000;">where</span>
<span style="font-style:italic;color:#408080;">&gt;     </span><span style="color:#0000ff;">get</span> <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="color:#b00040;">MC</span> <span style="color:#666666;">$</span> <span style="color:#0000ff;">\</span>s <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> return (s, <span style="color:#666666;">1.0</span>, s)
<span style="font-style:italic;color:#408080;">&gt;     </span><span style="color:#0000ff;">put</span> x <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="color:#b00040;">MC</span> <span style="color:#666666;">$</span> <span style="color:#0000ff;">\</span>s <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> return (x, <span style="color:#666666;">1.0</span>, <span style="color:#008000;">()</span>)
<span style="font-style:italic;color:#408080;">&gt; </span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="font-weight:bold;color:#008000;">instance</span> <span style="color:#b00040;">MonadMC</span> s (<span style="color:#b00040;">MC</span> s) <span style="font-weight:bold;color:#008000;">where</span>
<span style="font-style:italic;color:#408080;">&gt;     </span><span style="color:#0000ff;">choose</span> (a, b) <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="font-weight:bold;color:#008000;">let</span> r <span style="font-weight:bold;color:#aa22ff;">=</span> [a<span style="color:#666666;">..</span>b]
<span style="font-style:italic;color:#408080;">&gt;                         </span><span style="color:#0000ff;">p</span> <span style="font-weight:bold;color:#aa22ff;">=</span> recip <span style="color:#666666;">.</span> fromIntegral <span style="color:#666666;">.</span> length <span style="color:#666666;">$</span> r
<span style="font-style:italic;color:#408080;">&gt;                     </span><span style="font-weight:bold;color:#008000;">in</span> <span style="color:#b00040;">MC</span> <span style="color:#666666;">$</span> <span style="color:#0000ff;">\</span>s <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> map (<span style="color:#0000ff;">\</span>x <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> (s, p, x)) r
<span style="font-style:italic;color:#408080;">&gt; </span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="font-weight:bold;color:#008000;">type</span> <span style="color:#b00040;">Game</span> a <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="color:#b00040;">MC</span> <span style="color:#b00040;">GameState</span> a</pre>
<p>The idea is that we keep track of all possible destination states for a given state, with associated conditional probabilities. For those familiar with Eric Kidd&#8217;s <a href="http://www.randomhacks.net/articles/2007/02/21/refactoring-probability-distributions">series on probability monads</a>, this is basically:</p>
<pre style="font-size:140%;"><span style="font-weight:bold;color:#008000;">type</span> <span style="color:#b00040;">MC</span> s a <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="color:#b00040;">StateT</span> s (<span style="color:#b00040;">PerhapsT</span> <span style="color:#b00040;">[]</span> a)</pre>
<p>Now, how to get a transition matrix from such a monad? Of course, we have to require that the states are <a href="http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Ix.html">indexable</a>:</p>
<pre style="font-size:140%;"><span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">markov</span> <span style="font-weight:bold;color:#aa22ff;">::</span> <span style="color:#b00040;">Ix</span> s <span style="font-weight:bold;color:#aa22ff;">=&gt;</span>
<span style="font-style:italic;color:#408080;">&gt;           </span><span style="color:#b00040;">MC</span> s <span style="color:#008000;">()</span> <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> (s, s) <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> <span style="color:#b00040;">Array</span> (s, s) <span style="color:#b00040;">Double</span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">markov</span> (<span style="color:#b00040;">MC</span> m) r <span style="font-weight:bold;color:#aa22ff;">=</span> accumArray (<span style="color:#666666;">+</span>) <span style="color:#666666;">0.0</span> (double r) <span style="color:#666666;">$</span>
<span style="font-style:italic;color:#408080;">&gt;  	     	    </span><span style="color:#0000ff;">range</span> r <span style="color:#666666;">&gt;&gt;=</span> transitions
<span style="font-style:italic;color:#408080;">&gt;     </span><span style="font-weight:bold;color:#008000;">where</span>
<span style="font-style:italic;color:#408080;">&gt;       </span><span style="color:#0000ff;">mkAssoc</span> s (s', p, <span style="font-weight:bold;color:#008000;">_</span>) <span style="font-weight:bold;color:#aa22ff;">=</span> ((s, s'), p)
<span style="font-style:italic;color:#408080;">&gt;       </span><span style="color:#0000ff;">transitions</span> s <span style="font-weight:bold;color:#aa22ff;">=</span> map (mkAssoc s) <span style="color:#666666;">$</span> m s
<span style="font-style:italic;color:#408080;">&gt; 	</span><span style="color:#0000ff;">double</span> (a, b) <span style="font-weight:bold;color:#aa22ff;">=</span> ((a, a), (b, b))</pre>
<p>So we iterate over all states and use the probability values contained in the monad to fill in the array cells corresponding to the selected state pair.</p>
<p>To actually apply this to our Monopoly example, we need to make <code>GameState</code> indexable:</p>
<pre style="font-size:140%;"><span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">nextState</span> <span style="font-weight:bold;color:#aa22ff;">::</span> <span style="color:#b00040;">GameState</span> <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> <span style="color:#b00040;">GameState</span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">nextState</span> (<span style="color:#b00040;">GS</span> p d) <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="font-weight:bold;color:#008000;">if</span> d <span style="color:#666666;">==</span> <span style="color:#666666;">2</span>
<span style="font-style:italic;color:#408080;">&gt;                      </span><span style="font-weight:bold;color:#008000;">then</span> <span style="color:#b00040;">GS</span> (p <span style="color:#666666;">+</span> <span style="color:#666666;">1</span>) <span style="color:#666666;">0</span>
<span style="font-style:italic;color:#408080;">&gt;                      </span><span style="font-weight:bold;color:#008000;">else</span> <span style="color:#b00040;">GS</span> p (d <span style="color:#666666;">+</span> <span style="color:#666666;">1</span>)
<span style="font-style:italic;color:#408080;">&gt; </span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="font-weight:bold;color:#008000;">instance</span> <span style="color:#b00040;">Ix</span> <span style="color:#b00040;">GameState</span> <span style="font-weight:bold;color:#008000;">where</span>
<span style="font-style:italic;color:#408080;">&gt;     </span><span style="color:#0000ff;">range</span> (s1, s2) <span style="font-weight:bold;color:#aa22ff;">=</span> takeWhile (<span style="color:#666666;">&lt;=</span> s2) <span style="color:#666666;">.</span>
<span style="font-style:italic;color:#408080;">&gt;                      </span><span style="color:#0000ff;">iterate</span> nextState <span style="color:#666666;">$</span> s1
<span style="font-style:italic;color:#408080;">&gt;     </span><span style="color:#0000ff;">index</span> (s1, s2) s <span style="font-weight:bold;color:#aa22ff;">=</span>
<span style="font-style:italic;color:#408080;">&gt;         </span><span style="font-weight:bold;color:#008000;">let</span> poss <span style="font-weight:bold;color:#aa22ff;">=</span> (position s1, position s2)
<span style="font-style:italic;color:#408080;">&gt;         </span><span style="font-weight:bold;color:#008000;">in</span> index poss (position s) <span style="color:#666666;">*</span> <span style="color:#666666;">3</span> <span style="color:#666666;">+</span>
<span style="font-style:italic;color:#408080;">&gt;            </span><span style="color:#0000ff;">doubles</span> s <span style="color:#666666;">-</span> doubles s1
<span style="font-style:italic;color:#408080;">&gt;     </span><span style="color:#0000ff;">inRange</span> (s1, s2) s <span style="font-weight:bold;color:#aa22ff;">=</span> s1 <span style="color:#666666;">&lt;=</span> s <span style="color:#666666;">&amp;&amp;</span> s <span style="color:#666666;">&lt;=</span> s2
<span style="font-style:italic;color:#408080;">&gt;     </span><span style="color:#0000ff;">rangeSize</span> (s1, s2) <span style="font-weight:bold;color:#aa22ff;">=</span> index (s1, s2) s2 <span style="color:#666666;">+</span> <span style="color:#666666;">1</span></pre>
<p>then finally we can try:</p>
<pre style="font-size:140%;"><span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">monopoly</span> <span style="font-weight:bold;color:#aa22ff;">::</span> (<span style="color:#b00040;">GameState</span>, <span style="color:#b00040;">GameState</span>)
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">monopoly</span> <span style="font-weight:bold;color:#aa22ff;">=</span> (<span style="color:#b00040;">GS</span> <span style="color:#666666;">0</span> <span style="color:#666666;">0</span>, <span style="color:#b00040;">GS</span> <span style="color:#666666;">39</span> <span style="color:#666666;">2</span>)
<span style="font-style:italic;color:#408080;">&gt; </span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">initialState</span> <span style="font-weight:bold;color:#aa22ff;">::</span> <span style="color:#b00040;">Array</span> <span style="color:#b00040;">GameState</span> <span style="color:#b00040;">Double</span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">initialState</span> <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="font-weight:bold;color:#008000;">let</span> n <span style="font-weight:bold;color:#aa22ff;">=</span> rangeSize monopoly
<span style="font-style:italic;color:#408080;">&gt;                    </span><span style="color:#0000ff;">p</span> <span style="font-weight:bold;color:#aa22ff;">=</span> recip <span style="color:#666666;">$</span> fromIntegral n
<span style="font-style:italic;color:#408080;">&gt;                </span><span style="font-weight:bold;color:#008000;">in</span> listArray monopoly <span style="color:#666666;">$</span> replicate n p
<span style="font-style:italic;color:#408080;">&gt; </span>
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">statDistr</span> <span style="font-weight:bold;color:#aa22ff;">::</span> <span style="color:#b00040;">Int</span> <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> [(<span style="color:#b00040;">GameState</span>, <span style="color:#b00040;">Double</span>)]
<span style="font-style:italic;color:#408080;">&gt; </span><span style="color:#0000ff;">statDistr</span> n <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="font-weight:bold;color:#008000;">let</span> mat <span style="font-weight:bold;color:#aa22ff;">=</span> markov game monopoly
<span style="font-style:italic;color:#408080;">&gt;                   </span><span style="color:#0000ff;">distributions</span> <span style="font-weight:bold;color:#aa22ff;">=</span> iterate (<span style="color:#666666;">.*</span> mat)
<span style="font-style:italic;color:#408080;">&gt;                         </span><span style="color:#0000ff;">initialState</span>
<span style="font-style:italic;color:#408080;">&gt;                   </span><span style="color:#0000ff;">st</span> <span style="font-weight:bold;color:#aa22ff;">=</span> distributions <span style="color:#666666;">!!</span> n
<span style="font-style:italic;color:#408080;">&gt;               </span><span style="font-weight:bold;color:#008000;">in</span> assocs st</pre>
<p>where .* is a simple vector-matrix multiplication function:</p>
<pre style="font-size:140%;"><span style="font-style:italic;color:#408080;">&gt; </span><span style="font-weight:bold;color:#008000;">infixl</span> <span style="color:#666666;">5</span> <span style="color:#666666;">.*</span>
<span style="font-style:italic;color:#408080;">&gt; </span>(<span style="color:#666666;">.*</span>) <span style="font-weight:bold;color:#aa22ff;">::</span> (<span style="color:#b00040;">Ix</span> i, <span style="color:#b00040;">Num</span> a) <span style="font-weight:bold;color:#aa22ff;">=&gt;</span>
<span style="font-style:italic;color:#408080;">&gt;            </span><span style="color:#b00040;">Array</span> i a <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> <span style="color:#b00040;">Array</span> (i, i) a <span style="font-weight:bold;color:#aa22ff;">-&gt;</span> <span style="color:#b00040;">Array</span> i a
<span style="font-style:italic;color:#408080;">&gt; </span>(<span style="color:#666666;">.*</span>) x y <span style="font-weight:bold;color:#aa22ff;">=</span> array resultBounds
<span style="font-style:italic;color:#408080;">&gt;               </span>[(i, sum [x<span style="color:#666666;">!</span>k <span style="color:#666666;">*</span> y<span style="color:#666666;">!</span>(k,i) <span style="color:#666666;">|</span> k <span style="font-weight:bold;color:#aa22ff;">&lt;-</span> range (l,u)])
<span style="font-style:italic;color:#408080;">&gt;                </span><span style="color:#666666;">|</span> i <span style="font-weight:bold;color:#aa22ff;">&lt;-</span> range (l'',u'') ]
<span style="font-style:italic;color:#408080;">&gt;         </span><span style="font-weight:bold;color:#008000;">where</span> (l, u) <span style="font-weight:bold;color:#aa22ff;">=</span> bounds x
<span style="font-style:italic;color:#408080;">&gt;               </span>((l', l''), (u', u'')) <span style="font-weight:bold;color:#aa22ff;">=</span> bounds y
<span style="font-style:italic;color:#408080;">&gt;               </span><span style="color:#0000ff;">resultBounds</span>
<span style="font-style:italic;color:#408080;">&gt;                 </span><span style="color:#666666;">|</span> (l,u)<span style="color:#666666;">==</span>(l',u') <span style="font-weight:bold;color:#aa22ff;">=</span> (l'', u'')
<span style="font-style:italic;color:#408080;">&gt;                 </span><span style="color:#666666;">|</span> otherwise <span style="font-weight:bold;color:#aa22ff;">=</span> <span style="font-weight:bold;color:#d2413a;">error</span> <span style="color:#ba2121;">".*: incompatible bounds"</span></pre>
<p>Calling <code>statDistr 100</code> will return an association list of states with corresponding probability in an approximation of the stationary distribution, computed by applying the <a href="http://en.wikipedia.org/wiki/Power_method">power method</a> to the transition matrix. The number 100 is a pure guess, I don&#8217;t know how to estimate the number of iterations necessary for convergence, but that is out of the scope of this post, anyway.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pcapriotti.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pcapriotti.wordpress.com/46/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pcapriotti.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pcapriotti.wordpress.com/46/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pcapriotti.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pcapriotti.wordpress.com/46/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pcapriotti.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pcapriotti.wordpress.com/46/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pcapriotti.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pcapriotti.wordpress.com/46/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pcapriotti.wordpress.com&blog=806312&post=46&subd=pcapriotti&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://pcapriotti.wordpress.com/2008/10/16/monads-for-markov-chains/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/472181d606a709332975dcceb974eba9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">pcapriotti</media:title>
		</media:content>
	</item>
		<item>
		<title>Rewriting from scratch</title>
		<link>http://pcapriotti.wordpress.com/2008/04/27/rewriting-from-scratch/</link>
		<comments>http://pcapriotti.wordpress.com/2008/04/27/rewriting-from-scratch/#comments</comments>
		<pubDate>Sun, 27 Apr 2008 14:02:49 +0000</pubDate>
		<dc:creator>pcapriotti</dc:creator>
				<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://pcapriotti.wordpress.com/?p=40</guid>
		<description><![CDATA[I have recently come across this article (and those linked by it), while I was considering a rewrite for my own pet project.
While I tend to think that rewriting from scratch is usually a bad idea, if we are talking about open source projects, there&#8217;s another element you should take into account: how pleasurable it [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pcapriotti.wordpress.com&blog=806312&post=40&subd=pcapriotti&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>I have recently come across <a href="http://my.opera.com/Vorlath/blog/2007/09/25/code-rewrite-yes">this article</a> (and those linked by it), while I was considering a rewrite for my own pet project.</p>
<p>While I tend to think that rewriting from scratch is usually a bad idea, if we are talking about open source projects, there&#8217;s another element you should take into account: how pleasurable it is to work on it. If you end up with a big and hairy code base you cannot touch without suddenly feeling all sad and pessimistic about the fate of the world, you should realize that something has gone deeply wrong: you are supposed to work on your project for <em>fun</em> (yeah, to scratch an itch, maybe, too&#8230;), and when the fun stops, most of the reasons to continue disappear. You have no (paying) customers, you have no deadlines, you will be able (or unable, depending on what you do in the rest of your time) to pay your bills anyway.</p>
<p>At this point, either you throw everything into the garbage bin &#8211; which may be sad, disappointing and frustrating, both for you and your users &#8211; or you take whatever lessons you may have learned in the process, and use your extra wisdom to start from scratch a hopefully better and more mature design and implementation that won&#8217;t have those shortcomings that brought you to this miserable situation.</p>
<p>It will probably have other defects and issues, though, more subtle and harder to spot in an upfront design. You have to accept it. And you have to accept the fact that you may need to start from scratch once again in the future.</p>
<p>Here is a simple form you can use to announce your decision to start from scratch. Just copy-paste it into your blog, filling in the required fields. It may save you precious time that you will be able to spend on your n-th rewrite <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<pre>I'll rewrite my pet project from scratch because:

[ ] It's not modular enough
[ ] The original design didn't take __________________ into consideration
[ ] It's too slow
[ ] There is too much legacy code which I can't seem to get rid of
[ ] I want to write it in ____________________

----

[ ] And this time I'll use TDD/BDD

[ ] And this time it will be done right!

Signed (the developer)

_____________________________</pre>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/pcapriotti.wordpress.com/40/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/pcapriotti.wordpress.com/40/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pcapriotti.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pcapriotti.wordpress.com/40/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pcapriotti.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pcapriotti.wordpress.com/40/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pcapriotti.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pcapriotti.wordpress.com/40/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pcapriotti.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pcapriotti.wordpress.com/40/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pcapriotti.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pcapriotti.wordpress.com/40/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pcapriotti.wordpress.com&blog=806312&post=40&subd=pcapriotti&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://pcapriotti.wordpress.com/2008/04/27/rewriting-from-scratch/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/472181d606a709332975dcceb974eba9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">pcapriotti</media:title>
		</media:content>
	</item>
		<item>
		<title>Fighting zombies with a double fork</title>
		<link>http://pcapriotti.wordpress.com/2008/02/12/fighting-zombies-with-a-double-fork/</link>
		<comments>http://pcapriotti.wordpress.com/2008/02/12/fighting-zombies-with-a-double-fork/#comments</comments>
		<pubDate>Tue, 12 Feb 2008 01:39:01 +0000</pubDate>
		<dc:creator>pcapriotti</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[posix]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[zombies]]></category>

		<guid isPermaLink="false">http://pcapriotti.wordpress.com/?p=38</guid>
		<description><![CDATA[No, this post is not about a special weapon against Romero&#8217;s undeads (though that would be cool  , but about a trick I&#8217;ve just discovered after a lot of struggling with child processes that aren&#8217;t properly reaped by their parent.
Let me try to be a bit more specific: suppose you have a parent that [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pcapriotti.wordpress.com&blog=806312&post=38&subd=pcapriotti&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>No, this post is not about a special weapon against Romero&#8217;s undeads (though that would be cool <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> , but about a trick I&#8217;ve just discovered after a lot of struggling with child processes that aren&#8217;t properly reaped by their parent.<br />
Let me try to be a bit more specific: suppose you have a parent that needs to spawn two kinds of child processes. Processes of the first kind perform a computation and return to the parent immediately (so they are handled via a fork+exec+waitpid combination), while those of the second kind should be started, their pid recorded so that they may be killed later, and then forgotten.<br />
The question is: how to handle the second kind of subprocesses? If you just fork+exec, when you later kill them, you get zombie processes. If you ignore SIGCHLD (so auto-reaping is enabled) you can&#8217;t perform a blocking wait on the children of the first kind anymore. Handling SIGCHLD is perhaps possible, but I think you need to keep track of the PIDs of the spawned processes and do some magic in the handler. I didn&#8217;t manage to make this working.</p>
<p>What I did manage to get working is the following: just spawn the process in a temporary child process. This way the grandchild will be orphaned and won&#8217;t require a wait from its grandfather.</p>
<p>There are however some problems with this approach. Namely, the child needs to send the PID of its own child to the parent. I&#8217;ve accomplished that through a pipe. Here is some example code to better illustrate this technique:</p>
<pre class="brush: python;">
from subprocess import Popen, PIPE, STDOUT
import sys

def spawn(cmd):
    cmdline = ('python', __file__) + cmd
    return int(Popen(cmdline, stdout = PIPE).stdout.read())

if __name__ == '__main__':
    print Popen(sys.argv[1:], stdout = open('/dev/null', 'w'), stderr = STDOUT).pid
    sys.exit(0)</pre>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/pcapriotti.wordpress.com/38/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/pcapriotti.wordpress.com/38/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pcapriotti.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pcapriotti.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pcapriotti.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pcapriotti.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pcapriotti.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pcapriotti.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pcapriotti.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pcapriotti.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pcapriotti.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pcapriotti.wordpress.com/38/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pcapriotti.wordpress.com&blog=806312&post=38&subd=pcapriotti&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://pcapriotti.wordpress.com/2008/02/12/fighting-zombies-with-a-double-fork/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/472181d606a709332975dcceb974eba9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">pcapriotti</media:title>
		</media:content>
	</item>
		<item>
		<title>skema 0.1</title>
		<link>http://pcapriotti.wordpress.com/2007/11/19/skema-01/</link>
		<comments>http://pcapriotti.wordpress.com/2007/11/19/skema-01/#comments</comments>
		<pubDate>Mon, 19 Nov 2007 19:49:51 +0000</pubDate>
		<dc:creator>pcapriotti</dc:creator>
				<category><![CDATA[kde]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[skema]]></category>

		<guid isPermaLink="false">http://pcapriotti.wordpress.com/2007/11/19/skema-01/</guid>
		<description><![CDATA[I have just released skema, a very simple tool I wrote to automate some repetitive coding tasks. Nothing fancy, just a ruby script that expands ERB templates in a directory, reading variable values from the command line, configuration files, or interactively.
Its purpose is similar to kapptemplate (it already includes a minimal KDE application template), but [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pcapriotti.wordpress.com&blog=806312&post=36&subd=pcapriotti&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>I have just released <strong>skema</strong>, a very simple tool I wrote to automate some repetitive coding tasks. Nothing fancy, just a ruby script that expands <a href="http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/">ERB</a> templates in a directory, reading variable values from the command line, configuration files, or interactively.<br />
Its purpose is similar to <a href="http://kapptemplate.granroth.org/">kapptemplate</a> (it already includes a minimal KDE application template), but it may be faster to use for little things, and it is probably easier to create templates for it.<br />
Here is a <a href="http://capriotti.selfip.net/skema-0.1.tar.gz">tarball</a> for those of you who want to try it out. You can find a short tutorial in the README file that should be enough to get you started.<br />
Here is a screenshot of skema in interactive mode while expanding the kapp template:<br />
<a href="http://pcapriotti.files.wordpress.com/2007/11/skema-shot.png" title="screenshot of skema 0.1"><img src="http://pcapriotti.files.wordpress.com/2007/11/skema-shot.png" alt="screenshot of skema 0.1" /></a></p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/pcapriotti.wordpress.com/36/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/pcapriotti.wordpress.com/36/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pcapriotti.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pcapriotti.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pcapriotti.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pcapriotti.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pcapriotti.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pcapriotti.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pcapriotti.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pcapriotti.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pcapriotti.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pcapriotti.wordpress.com/36/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pcapriotti.wordpress.com&blog=806312&post=36&subd=pcapriotti&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://pcapriotti.wordpress.com/2007/11/19/skema-01/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/472181d606a709332975dcceb974eba9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">pcapriotti</media:title>
		</media:content>

		<media:content url="http://pcapriotti.files.wordpress.com/2007/11/skema-shot.png" medium="image">
			<media:title type="html">screenshot of skema 0.1</media:title>
		</media:content>
	</item>
		<item>
		<title>Some thoughts on git</title>
		<link>http://pcapriotti.wordpress.com/2007/10/08/some-thoughts-on-git/</link>
		<comments>http://pcapriotti.wordpress.com/2007/10/08/some-thoughts-on-git/#comments</comments>
		<pubDate>Mon, 08 Oct 2007 13:58:29 +0000</pubDate>
		<dc:creator>pcapriotti</dc:creator>
				<category><![CDATA[git]]></category>
		<category><![CDATA[kde]]></category>
		<category><![CDATA[tagua]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[distributed vcs]]></category>
		<category><![CDATA[modularity]]></category>
		<category><![CDATA[unix]]></category>

		<guid isPermaLink="false">http://pcapriotti.wordpress.com/2007/10/08/some-thoughts-on-git/</guid>
		<description><![CDATA[As I mentioned in a previous post, we started using git for managing Tagua source code. There&#8217;s currently a lot of controversy in the topic of distributed versus centralized VCS&#8217;s, and I feel like expressing my own ideas, too. 
I&#8217;m no git guru (yet), so please don&#8217;t get offended if I missed something in my [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pcapriotti.wordpress.com&blog=806312&post=34&subd=pcapriotti&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>As I mentioned in a previous post, we started using git for managing Tagua source code. There&#8217;s currently a lot of controversy in the topic of distributed versus centralized VCS&#8217;s, and I feel like expressing my own ideas, too. <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
I&#8217;m no git guru (yet), so please don&#8217;t get offended if I missed something in my criticism. I hope to generate a fruitful discussion, because I really think that the VCS is an important element in the development of an open source project.</p>
<h3>Why git rules</h3>
<ul>
<li>It&#8217;s decentralized. I fully agree with Linus on this point: the decentralized model is superior, for various reasons I won&#8217;t talk about in detail here.</li>
<li>It&#8217;s simple. I don&#8217;t understand why people keep complaining about git being overly complicated. The object model is fairly straightforward, as soon as you stop thinking about revisions the cvs/svn way, and branching/merging is trivial.</li>
<li>The object model is very well designed, flexible and useful.</li>
</ul>
<h3>Why git sucks</h3>
<p>Well, git has a number of minor (?) defects, like portability issues, impossibility of doing partial checkouts (actually I think this is a problem with all the decentralized VCS&#8217;s) and stuff like that, but let me concentrate on those issues which are fundamental to git as an open source project, and are unlikely to be addressed in the future:</p>
<ul>
<li>It is written in (unreadable) C. I don&#8217;t want to start a flame war (really!), but browsing through git&#8217;s code is a painful experience. Huge .c files with tons of big functions with no apparent structure and almost no comment. Ubiquitous micro-management stuff for handling manually allocated buffers. In other words&#8230; a mess.</li>
<li>It (ab)uses the UNIX philosophy. <em>Do one thing, and do it well</em>. Yeah, of course it&#8217;s a great idea, but maybe they shouldn&#8217;t have taken it too literally. I mean, if we talk about modularity and reusable components, I&#8217;m all for it, but it doesn&#8217;t mean you have to make a different executable for each task (even low level ones that should be invisible to the end user) and chain them together via text pipes and bash scripts!</li>
<li>It&#8217;s not reusable by third party applications, at least not in any efficient/convenient way. If you want to build a higher-level abstraction over git (a so-called porcelain), you need to fork out every now and then to get input from git, and then parse its textual output. Yes, I know about libgit.a, but that&#8217;s not really usable as a library (half of git functions call <code>exit</code> on failure) and has no API documentation at all.</li>
</ul>
<p>That said, I have to admit that most of its defects aren&#8217;t that important if you are just going to use it, and not develop it. However, using something you have problems inspecting and modifying feels a bit like using a closed source product&#8230;</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/pcapriotti.wordpress.com/34/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/pcapriotti.wordpress.com/34/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pcapriotti.wordpress.com/34/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pcapriotti.wordpress.com/34/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pcapriotti.wordpress.com/34/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pcapriotti.wordpress.com/34/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pcapriotti.wordpress.com/34/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pcapriotti.wordpress.com/34/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pcapriotti.wordpress.com/34/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pcapriotti.wordpress.com/34/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pcapriotti.wordpress.com/34/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pcapriotti.wordpress.com/34/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pcapriotti.wordpress.com&blog=806312&post=34&subd=pcapriotti&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://pcapriotti.wordpress.com/2007/10/08/some-thoughts-on-git/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/472181d606a709332975dcceb974eba9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">pcapriotti</media:title>
		</media:content>
	</item>
		<item>
		<title>KBoard is dead. Long live Tagua!</title>
		<link>http://pcapriotti.wordpress.com/2007/07/19/kboard-is-dead-long-live-tagua/</link>
		<comments>http://pcapriotti.wordpress.com/2007/07/19/kboard-is-dead-long-live-tagua/#comments</comments>
		<pubDate>Thu, 19 Jul 2007 11:44:43 +0000</pubDate>
		<dc:creator>pcapriotti</dc:creator>
				<category><![CDATA[kboard]]></category>
		<category><![CDATA[kde]]></category>
		<category><![CDATA[tagua]]></category>

		<guid isPermaLink="false">http://pcapriotti.wordpress.com/2007/07/19/kboard-is-dead-long-live-tagua/</guid>
		<description><![CDATA[We finally made a decision, and named the project Tagua. Thanks to all the people who suggested possible names, and expecially to Riccardo Iaconelli who came up with the definitive one.
I&#8217;m now doing a global s/kboard/tagua/g on webpages, code, tracker, cron jobs, git repository&#8230;
Ah, yes, I forgot to mention that we moved the project to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pcapriotti.wordpress.com&blog=806312&post=33&subd=pcapriotti&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>We finally made a decision, and named the project <strong><a href="http://en.wikipedia.org/wiki/Tagua">Tagua</a></strong>. Thanks to all the people who suggested possible names, and expecially to <a href="http://blog.ruphy.org">Riccardo Iaconelli</a> who came up with the definitive one.<br />
I&#8217;m now doing a global <code>s/kboard/tagua/g</code> on webpages, code, tracker, cron jobs, git repository&#8230;</p>
<p>Ah, yes, I forgot to mention that we moved the project to <a href="http://git.or.cz/">git</a> when we resumed the development at Akademy. There has been a <a href="http://lists.kde.org/?t=118415921300005&amp;r=1&amp;w=2">long thread</a> on kde-core-devel discussing the adoption of git by subprojects, and there emerged that moving away from the KDE svn (though apparently discouraged) does not mean parting from the KDE project. I&#8217;ll probably talk about our experience with git in a dedicated post.</p>
<p>So, if you want to try the development version of Tagua, either grab a nightly snapshot (temporarely located <a href="http://tagua.ath.cx/tarballs/latest.tar.gz">here</a>), or clone our main repository:</p>
<pre>
git clone http://repo.or.cz/r/tagua.git</pre>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/pcapriotti.wordpress.com/33/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/pcapriotti.wordpress.com/33/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pcapriotti.wordpress.com/33/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pcapriotti.wordpress.com/33/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pcapriotti.wordpress.com/33/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pcapriotti.wordpress.com/33/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pcapriotti.wordpress.com/33/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pcapriotti.wordpress.com/33/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pcapriotti.wordpress.com/33/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pcapriotti.wordpress.com/33/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pcapriotti.wordpress.com/33/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pcapriotti.wordpress.com/33/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pcapriotti.wordpress.com&blog=806312&post=33&subd=pcapriotti&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://pcapriotti.wordpress.com/2007/07/19/kboard-is-dead-long-live-tagua/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/472181d606a709332975dcceb974eba9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">pcapriotti</media:title>
		</media:content>
	</item>
		<item>
		<title>KBoard: an update</title>
		<link>http://pcapriotti.wordpress.com/2007/07/18/kboard-an-update/</link>
		<comments>http://pcapriotti.wordpress.com/2007/07/18/kboard-an-update/#comments</comments>
		<pubDate>Wed, 18 Jul 2007 01:13:03 +0000</pubDate>
		<dc:creator>pcapriotti</dc:creator>
				<category><![CDATA[kboard]]></category>
		<category><![CDATA[kde]]></category>

		<guid isPermaLink="false">http://pcapriotti.wordpress.com/2007/07/18/kboard-an-update/</guid>
		<description><![CDATA[KBoard is a project by Maurizio and myself for a generic board game application. It started back in October 2005, and progressed slowly but steady until the end of 2006. After then it was left starving on the playground, basically untouched until a few days ago.
After a prolific discussion at Akademy, we are now back [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pcapriotti.wordpress.com&blog=806312&post=24&subd=pcapriotti&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>KBoard is a project by <a href="http://myrizio.wordpress.com">Maurizio</a> and myself for a generic board game application. It started back in October 2005, and progressed slowly but steady until the end of 2006. After then it was left starving on the playground, basically untouched until a few days ago.<br />
After a prolific discussion at Akademy, we are now back developing KBoard at full speed. Here are a couple of screenshots showing our progresses so far:</p>
<p><a href="http://pcapriotti.files.wordpress.com/2007/07/kboard.png" title="KBoard"><img src="http://pcapriotti.files.wordpress.com/2007/07/kboard_thumb.png" alt="KBoard" /></a></p>
<p><a href="http://pcapriotti.files.wordpress.com/2007/07/kboard1.png" title="KBoard"><img src="http://pcapriotti.files.wordpress.com/2007/07/kboard1_thumb.png" alt="KBoard" /></a></p>
<p>Compare them with the old <a href="http://kboard.sourceforge.net/wiki/index.php/Screenshots">screenshots</a> and you&#8217;ll see how much has been done in just a few weeks: the main layout and the clock are now themable via <a href="http://www.lua.org">Lua</a> scripts, just like the chessboard and pieces.<br />
I shall thank Maurizio for this astonishing work, and generally for his invaluable Lua theme loader, which is one of the finest pieces of code in KBoard.</p>
<p>By the way, most of the recent changes are actually invisible to the user, and concern the API used by the graphical interface to communicate with game plugins (called <em>variants</em>). I recently worked (not that much) on the animation stuff, and ported three games to the new API. Maurizio made the whole refactoring of the code using the old API at akademy, and revised the concepts around the pool (i.e. the place where captured pieces end up in games like Shogi and Crazyhouse).</p>
<p>We plan to release KBoard 1.0 by the end of the year. It might be an optimistic estimate, but if we continue to work with this speed, it should be actually possible. There is a lot of things to fix, but the planned features are almost all there. Needless to say, any help (developers, artists) would be really appreciated. <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>At the moment, our biggest dilemma is the name. We decided that the name should be changed (KBoard is ugly and doesn&#8217;t even make clear what the application is about), but after a whole day of awfully poor proposals, we still have to find a decent alternative. So you if have a nice name in mind (not necessarily starting with k, think about Phonon, Plasma, Solid&#8230; those are good names!) please tell us!</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/pcapriotti.wordpress.com/24/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/pcapriotti.wordpress.com/24/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pcapriotti.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pcapriotti.wordpress.com/24/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pcapriotti.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pcapriotti.wordpress.com/24/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pcapriotti.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pcapriotti.wordpress.com/24/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pcapriotti.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pcapriotti.wordpress.com/24/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pcapriotti.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pcapriotti.wordpress.com/24/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pcapriotti.wordpress.com&blog=806312&post=24&subd=pcapriotti&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://pcapriotti.wordpress.com/2007/07/18/kboard-an-update/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/472181d606a709332975dcceb974eba9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">pcapriotti</media:title>
		</media:content>

		<media:content url="http://pcapriotti.files.wordpress.com/2007/07/kboard_thumb.png" medium="image">
			<media:title type="html">KBoard</media:title>
		</media:content>

		<media:content url="http://pcapriotti.files.wordpress.com/2007/07/kboard1_thumb.png" medium="image">
			<media:title type="html">KBoard</media:title>
		</media:content>
	</item>
		<item>
		<title>Canvas adapter and plasma</title>
		<link>http://pcapriotti.wordpress.com/2007/06/05/canvas-adapter-and-plasma/</link>
		<comments>http://pcapriotti.wordpress.com/2007/06/05/canvas-adapter-and-plasma/#comments</comments>
		<pubDate>Tue, 05 Jun 2007 16:08:54 +0000</pubDate>
		<dc:creator>pcapriotti</dc:creator>
				<category><![CDATA[kde]]></category>
		<category><![CDATA[kgamecanvas]]></category>
		<category><![CDATA[plasma]]></category>

		<guid isPermaLink="false">http://pcapriotti.wordpress.com/2007/06/05/canvas-adapter-and-plasma/</guid>
		<description><![CDATA[I&#8217;ve finally finished polishing the code of KGameCanvasAdapter, a hundred lines of straightforward code that stand as a bridge between KGameCanvas code and any QPainter based drawing system, including of course QGV.
The only test case for the adapter is a port of my kollision game to plasma. Porting was very easy: it was just a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pcapriotti.wordpress.com&blog=806312&post=23&subd=pcapriotti&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>I&#8217;ve finally finished polishing the code of KGameCanvasAdapter, a hundred lines of straightforward code that stand as a bridge between KGameCanvas code and any QPainter based drawing system, including of course QGV.</p>
<p>The only test case for the adapter is a port of my <a href="http://websvn.kde.org/trunk/playground/games/kollision/">kollision</a> game to plasma. Porting was very easy: it was just a matter of having the MainArea class inherit from Plasma::Applet and KGameCanvasAdapter instead of QWidget. The resulting applet is not really a game, at the moment: it is just a box with bouncing red balls.<br />
However, I think it&#8217;s a good test for both my adapter and plasma, since it can show how well plasma performs with CPU intensive plasmoids. Here is a short screencast of the kollision plasmoid in action.</p>
<p><span style="text-align:center; display: block;"><a href="http://pcapriotti.wordpress.com/2007/06/05/canvas-adapter-and-plasma/"><img src="http://img.youtube.com/vi/rK5rhHnDE0M/2.jpg" alt="" /></a></span></p>
<p>The code is available in a git repository:</p>
<pre>
git clone http://kollision.ath.cx/plasma.git plasma</pre>
<p>will download the whole patched plasma directory. To compile it, you should move it inside a kdebase/workspace working copy, so that it uses the existing cmake build system of kdebase.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/pcapriotti.wordpress.com/23/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/pcapriotti.wordpress.com/23/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pcapriotti.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pcapriotti.wordpress.com/23/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pcapriotti.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pcapriotti.wordpress.com/23/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pcapriotti.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pcapriotti.wordpress.com/23/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pcapriotti.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pcapriotti.wordpress.com/23/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pcapriotti.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pcapriotti.wordpress.com/23/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pcapriotti.wordpress.com&blog=806312&post=23&subd=pcapriotti&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://pcapriotti.wordpress.com/2007/06/05/canvas-adapter-and-plasma/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/472181d606a709332975dcceb974eba9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">pcapriotti</media:title>
		</media:content>

		<media:content url="http://img.youtube.com/vi/rK5rhHnDE0M/2.jpg" medium="image" />
	</item>
		<item>
		<title>KBattleship: almost ready</title>
		<link>http://pcapriotti.wordpress.com/2007/04/13/kbattleship-almost-ready/</link>
		<comments>http://pcapriotti.wordpress.com/2007/04/13/kbattleship-almost-ready/#comments</comments>
		<pubDate>Fri, 13 Apr 2007 21:39:47 +0000</pubDate>
		<dc:creator>pcapriotti</dc:creator>
				<category><![CDATA[kbattleship]]></category>
		<category><![CDATA[kde]]></category>

		<guid isPermaLink="false">http://pcapriotti.wordpress.com/2007/04/13/kbattleship-almost-ready/</guid>
		<description><![CDATA[This week I&#8217;ve been hacking quite a lot on KBattleship, adding almost all required features: a decent AI, network play and sounds. While Riccardo is working on KWelcomeScreen, a library class inspired by this blog post by Johann, I&#8217;m going to make some minor adjustments, add small missing features like scoring, and if everything goes [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pcapriotti.wordpress.com&blog=806312&post=22&subd=pcapriotti&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>This week I&#8217;ve been hacking quite a lot on KBattleship, adding almost all required features: a decent AI, network play and sounds. While Riccardo is working on KWelcomeScreen, a library class inspired by <a href="http://johann.pwsp.net/2007/04/09/a-new-game-starter/">this blog post</a> by Johann, I&#8217;m going to make some minor adjustments, add small missing features like scoring, and if everything goes well I guess we can move the application to kdereview within next week.<br />
This is a screenshot showing a game between the old KBattleship and my rewrite:<br />
<a href="http://linuz.sns.it/~paolo/kbs3.png" title="KBS4 screenshot"><img src="http://linuz.sns.it/~paolo/kbs3-thumb.png" alt="KBS4 screenshot" /></a></p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/pcapriotti.wordpress.com/22/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/pcapriotti.wordpress.com/22/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pcapriotti.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pcapriotti.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pcapriotti.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pcapriotti.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pcapriotti.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pcapriotti.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pcapriotti.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pcapriotti.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pcapriotti.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pcapriotti.wordpress.com/22/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pcapriotti.wordpress.com&blog=806312&post=22&subd=pcapriotti&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://pcapriotti.wordpress.com/2007/04/13/kbattleship-almost-ready/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/472181d606a709332975dcceb974eba9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">pcapriotti</media:title>
		</media:content>

		<media:content url="http://linuz.sns.it/~paolo/kbs3-thumb.png" medium="image">
			<media:title type="html">KBS4 screenshot</media:title>
		</media:content>
	</item>
		<item>
		<title>Dynamic types and virtual inner types</title>
		<link>http://pcapriotti.wordpress.com/2007/04/05/dynamic-types-and-virtual-inner-types/</link>
		<comments>http://pcapriotti.wordpress.com/2007/04/05/dynamic-types-and-virtual-inner-types/#comments</comments>
		<pubDate>Thu, 05 Apr 2007 11:18:23 +0000</pubDate>
		<dc:creator>pcapriotti</dc:creator>
				<category><![CDATA[c++]]></category>
		<category><![CDATA[concepts]]></category>

		<guid isPermaLink="false">http://pcapriotti.wordpress.com/2007/04/05/dynamic-types-and-virtual-inner-types/</guid>
		<description><![CDATA[The concept based polymorphism I tried to explain in my previous post can be more conveniently expressed with another syntax which avoids concepts at all.
The key observation is that runtime polymorphism and F-bounded polymorphism are very similar in nature, and, to some extent, the latter can be implemented using the former. If I have understood [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pcapriotti.wordpress.com&blog=806312&post=21&subd=pcapriotti&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>The <em>concept based polymorphism</em> I tried to explain in my previous post can be more conveniently expressed with another syntax which avoids concepts at all.</p>
<p>The key observation is that runtime polymorphism and F-bounded polymorphism are very similar in nature, and, to some extent, the latter can be implemented using the former. If I have understood correctly, that is exactly how the Java virtual machine implements generics.</p>
<p>For example, suppose you have an abstract class <code>Shape</code> with a virtual function <code>draw</code>, and several concrete classes like <code>Square</code>, <code>Circle</code>, <code>Triangle</code>, which override <code>draw</code>.<br />
Client code using runtime polymorphism would look like:</p>
<pre>void render(Shape* shape)
{
  shape-&gt;draw();
}</pre>
<p>while using generic programming one could write:</p>
<pre>template &lt;typename S&gt;
where Inherits&lt;S, Shape&gt;
void render(S* s)
{
  s-&gt;draw();
}</pre>
<p>assuming that the concept Inherits&lt;T, U&gt; is verified when T inherits from U (possibly indirectly). An approximation for Inherits is</p>
<pre>auto concept Inherits&lt;typename T, typename U&gt;
{
  // T can be implicitly converted to U
  T::operator U();
}</pre>
<p>Using the generic code in such situations should probably be considered a mistake, because if one wants to use template based polymorphism, defining the abstract class Shape is pointless. It would be better to directly define a ShapeConcept having a member function draw.</p>
<p>However, the example suggests that a syntax resembling templates could be used to express runtime polymorphism:</p>
<pre>template &lt;Shape! S&gt;
void render(S* s)
{
  s-&gt;draw();
}</pre>
<p>the idea being that S is the runtime type of <code>s</code>. The compiler could instantiate the template immediately and implement the body just like a <code>Shape</code> pointer were used instead of <code>S</code>. Here <code>S</code> is not really a type, since for example expressions like</p>
<pre>new S</pre>
<p>should be rejected; let&#8217;s call things like <code>S</code> <strong>dynamic types</strong>. They behave much like incomplete types (cannot be instantiated directy, sizeof cannot be called on them), but are a different beast: for the purpose of typechecking they are just subtypes of their <strong>parent concept</strong> (<code>Shape</code>, in this example), but for code generation they are considered equivalent to it.</p>
<p>Why could all of this syntax be possibly useful? Well, when using ordinary abstract classes, it does not really add anything to the language, but it shows its power when another (more than syntactical) extension is introduced: <strong>virtual inner types</strong>.</p>
<p>Just like the name suggests, virtual inner types are inner types which behave polymorphically. The typical (and motivating) example here is still that of the abstract factory. So suppose you have the following abstract factory:</p>
<pre>class AbstractAnimal;
class AbstractFood;

class AbstractFactory
{
public:
  virtual AbstractAnimal* createAnimal() = 0;
  virtual AbstractFood* createFood() = 0;
};</pre>
<p>and the following abstract products:</p>
<pre>class AbstractAnimal
{
public:
  virtual void eat(Food*) = 0;
};

class AbstractFood
{
public:
  virtual int quality() const = 0;
};</pre>
<p>As explained in my previous posts [1] [2], there&#8217;s no way to explain to the compiler that the <code>Food</code> that an animal is able to eat is only that created by the same factory which created that very animal.<br />
Virtual inner types could be used to solve the problem:</p>
<pre>class AbstractAnimal;
class AbstractFood;

class AbstractFactory
{
public:
  virtual typedef AbstractAnimal Animal;
  virtual typedef AbstractFood Food;
  virtual Animal* createAnimal() = 0;
  virtual Food* createFood() = 0;
};

class AbstractAnimal
{
public:
  virtual typedef AbstractFactory Factory;
  virtual void eat(Factory::Food* food) = 0;
};

class AbstractFood
{
public:
  virtual typedef AbstractFactory Factory; // unused, only here for completeness
  virtual int quality() const = 0;
};</pre>
<p>The idea is that <code>virtual typedef Base X</code> forces inherited class to define an inner type <code>X</code> inheriting from <code>Base</code>. Furthermore, this type behaves polymorphically (the type itself, not only instances!). That means that if <code>A</code> is a dynamic type with parent <code>AbstractAnimal</code>, then <code>A::Factory</code> is the correct dynamic type with parent <code>AbstractFactory</code>.</p>
<p>To explain this fact in more detail, let&#8217;s continue the example:</p>
<pre>class Cow;
class Grass;

class CowFactory : public AbstractFactory
{
public:
  typedef Cow Animal;
  typedef Grass Food;
  Cow* createAnimal();
  Grass* createFood();
};

class Cow : public Animal
{
public:
  typedef CowFactory Factory;
  void eat(Grass* grass);
};

class Grass : public Food
{
public:
  typedef CowFactory Factory;
  int quality() const;
};</pre>
<p>notice that we have defined inner types corresponding to the virtual typedefs of parent classes. Besides, the argument to eat is <code>Grass</code> and not <code>AbstractFood</code>.<br />
Client code, in fact, cannot simply pass an <code>AbstractFood</code> object to the <code>eat</code> member function. The following function should not compile:</p>
<pre>void feed(AbstractAnimal* animal, AbstractFood* food)
{
  animal-&gt;eat(food);
}</pre>
<p>but can be fixed with the use of dynamic types</p>
<pre>template &lt;AbstractFactory! Factory&gt;
void feed(Factory::Animal* animal, Factory::Food* food)
{
  animal-&gt;eat(food);
}</pre>
<p>expressing the fact that both <code>animal</code> and <code>food</code> come from the same factory of dynamic type Factory. The food parameter (actually stored in an <code>AbstractFood</code> variable), is statically downcasted to <code>Grass</code> before being passed to the <code>eat</code> member function. The static typechecking via dynamic types ensures that such a downcast is always safe, so there is no need to perform a dynamic cast.</p>
<p>These ideas for a language extension are essentially equivalent to the ones expressed in the previous post, but seem to require less drastic changes in compiler implementations. Furthermore, they don&#8217;t use concepts, so it could be even implemented on top of the existing gcc.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/pcapriotti.wordpress.com/21/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/pcapriotti.wordpress.com/21/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pcapriotti.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pcapriotti.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pcapriotti.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pcapriotti.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pcapriotti.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pcapriotti.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pcapriotti.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pcapriotti.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pcapriotti.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pcapriotti.wordpress.com/21/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pcapriotti.wordpress.com&blog=806312&post=21&subd=pcapriotti&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://pcapriotti.wordpress.com/2007/04/05/dynamic-types-and-virtual-inner-types/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/472181d606a709332975dcceb974eba9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">pcapriotti</media:title>
		</media:content>
	</item>
	</channel>
</rss>