<?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>Mediocre To The Core</title>
	<atom:link href="http://kapilash.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://kapilash.wordpress.com</link>
	<description>(non-tail) recursive brooding on programming (languages)</description>
	<lastBuildDate>Thu, 07 May 2009 19:12:18 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='kapilash.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/c3161cd1c3aa479ff4cb0e58b7f7f650?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>Mediocre To The Core</title>
		<link>http://kapilash.wordpress.com</link>
	</image>
			<item>
		<title>Are the Knight Riders totally out of Semis?</title>
		<link>http://kapilash.wordpress.com/2009/05/07/are-the-knight-riders-totally-out-of-semis/</link>
		<comments>http://kapilash.wordpress.com/2009/05/07/are-the-knight-riders-totally-out-of-semis/#comments</comments>
		<pubDate>Thu, 07 May 2009 19:04:55 +0000</pubDate>
		<dc:creator>kapilash</dc:creator>
				<category><![CDATA[haskell]]></category>

		<guid isPermaLink="false">http://kapilash.wordpress.com/?p=29</guid>
		<description><![CDATA[Much as I hate the phrase “The Tournament is wide Open” (which ranks right up there with “DLF maximum” and “Citi moment of success” in terms of irritability and frequency), especially when I have to hear it from the likes of Ravi Shastry during one of those fugly presentation ceremonies, am enough intrigued by it [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kapilash.wordpress.com&blog=1696932&post=29&subd=kapilash&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Much as I hate the phrase “<a title="the official site of the IPL" href="http://iplt20.com/" target="_blank">The Tournament is wide Open</a>” (which ranks right up there with “DLF maximum” and “Citi moment of success” in terms of irritability and frequency), especially when I have to hear it from the likes of Ravi Shastry during one of those fugly presentation ceremonies, am enough intrigued by it to see if one can apply one&#8217;s <em>haskellfu</em> to throw more light on the alleged width of the tournament&#8217;s opening.</p>
<p>In short, I want a (haskell) program that takes as input:</p>
<ol class="enumerate" type="1">
<li class="li-enumerate"> points table and</li>
<li class="li-enumerate">future matches</li>
<li class="li-enumerate">A team name</li>
</ol>
<p>and can answer the following question :</p>
<p><strong>under what conditions can the team reach the last four?</strong></p>
<p>Assuming that at the end of each match the net run rate(NRR) will be incremented by 0.5 for the winner and decremented by 0.5 for the loser and that a match could also result in a draw (thanks to the the rain),in which case the teams share a point each (and with no change in the NRRs), the <em>tree</em> of possibilities will have a small matter of 3<sup>22</sup> nodes (considering there are 22 more matches to go , as I type this).  And 3<sup>20</sup> is <em>just</em> <strong>348,67,84,401</strong> ! I know for sure I would not be able to write the program in java/C++ as easily as  I can do it in Haskell.</p>
<p>So, Here I go,</p>
<pre class="verbatim">module Main where

import System.IO

import Data.Tree

import System.Environment

import qualified Data.Map as M
import qualified Data.List as L</pre>
<p>A match is a record of two fields teamA , teamB and points won by teamA and points won by teamB</p>
<pre class="verbatim">data Match = Match (String,Int) (String, Int)

                deriving Show</pre>
<p>Each team has a unique identifier to represent it, a collection of points and net-run rate</p>
<p>The teams can be compared on the basis of their points. If the points are identical, then their net-run rates are identified</p>
<pre class="verbatim">data Team = Team{teamName:: String,

                 teamScore      :: Int,

                 teamNetRunRate :: Float

                }

                deriving (Eq,Show)

compTeams (Team _ t1 n1) (Team _ t2 n2)

   = if (t1 &gt; t2) then GT

     else if (t1 &lt; t2) then LT

          else if (n1 &gt; n2) then GT

               else if (n1 &lt; n2) then LT

                    else EQ

instance Ord Team where

 compare  = compTeams</pre>
<p>we can also add three functions to the team that lets us add a win, lose and a draw</p>
<pre class="verbatim">addWin (Team t1 s r) = Team t1 (s + 2) (r + 0.5)

addLoss (Team t1 s r) = Team t1 s (r - 0.5)

addDraw (Team t1 s r) = Team t1 (s+1) r</pre>
<p>A tournament can be defined as a list of matches that were already played and a list of planned clashes between teams.<br />
However, I will also need a map between String and a team in order to use just the strings</p>
<pre class="verbatim">data Tournament = Tourney { teamMap :: M.Map String Team,

                            played  :: [Match],

                            toPlay  :: [(String,String)]

                          }

                      deriving Show</pre>
<p>Thus, this <strong>tournament</strong> presents a snapshot of the tournament at any given instant.<br />
Given these, identifying the top 4 is trivial</p>
<pre class="verbatim">topFour :: Tournament  -&gt; [Team]

topFour t = drop  4 (L.sort $ M.elems $ teamMap t)</pre>
<p>To conduct a match, we need to take a potential clash out of the “toPlay” list, convert it into a Match and add it to<br />
the played list and then update the teamMap with appropriate points depending on who won the particular match.<br />
In order to do so, we need a new data type to indicate the result of a match</p>
<pre class="verbatim">data MatchRes = AWon | BWon | Draw</pre>
<p>As mentioned earlier, conducting a match is akin to taking a given tournament and a result and getting a new snapshot of the tournament.</p>
<pre class="verbatim">conductMatch :: Tournament -&gt; MatchRes -&gt; Tournament

conductMatch t@(Tourney _ _ []) _   = t -- should it be an error

conductMatch t@(Tourney teams pld topl) mres  

  =   Tourney (updateTeams teams newMatch) (newMatch:pld) (tail topl)

       where newMatch = clashResToMatch (head topl) mres</pre>
<p>The two functions used above are defined below:</p>
<pre class="verbatim">clashResToMatch (s1,s2) AWon = Match (s1,2) (s2, 0)

clashResToMatch (s1,s2) BWon = Match (s1,0) (s2, 2)

clashResToMatch (s1, s2) _   = Match (s1, 1) (s2, 1)

updateTeams tMap (Match (t1,p1) (t2,p2))

  = addPointsToTeam t2 p2 (addPointsToTeam t1 p1 tMap)

addPointsToTeam t1 0 tMap = M.update (\x -&gt; Just $ addLoss x) t1 tMap

addPointsToTeam t1 1 tMap = M.update (\x -&gt; Just $ addDraw x) t1 tMap

addPointsToTeam t1 2 tMap = M.update (\x -&gt; Just $ addWin x) t1 tMap

addPointsToTeam _ _ _     = error "Invalid points in addPointsToTeam"</pre>
<p>Now in order to generate all the combinations, we need a function “explode”, that takes a tournament and gives a list of tournaments such that<br />
in each of these we have one possible result.</p>
<pre class="verbatim">explode (Tourney _ _ []) = []

explode t = map (conductMatch t) [AWon, BWon, Draw]</pre>
<p>Once the “explode” is in place, creating a tournament “tree” which provides all the possible combinations is very simple:</p>
<pre class="verbatim">tourneyTree t = Node t (map tourneyTree (explode t))

getLeaves (Node a []) = [a]

getLeaves (Node a xs) = concatMap getLeaves xs</pre>
<p>We are left with dealing with the input files and accessing the filter, which is pretty straight forward.</p>
<pre class="verbatim">main = do args &lt;- getArgs

          case args of 

            (i1:i2:t:[])   -&gt; do tourney &lt;- readInput i1 i2

                                 let lvs = filter (\x -&gt; hasTeamInTopFour t x) (getLeaves $ tourneyTree tourney)

                                 case lvs of

                                   (hd:rst) -&gt; do print hd

                                   []  -&gt; do print "No chance, dude"

            _        -&gt; do usage

usage = do print "Usage:"

           print "TWOpen InputFile outputFile &lt;Team Name&gt;"

           print "Team Name is one of : Delhi, Mumbai, Chennai, Kolkata, Hyd, Blore, Jaipur, Mohali"

hasTeamInTopFour tName t = tName `elem` (map teamName $ topFour t)</pre>
<p>Here, readInput is an IO action that takes a couple of files and returns the tournament snapshot as depicted in the input.</p>
<p>It is trivial as am using the built-in “read” function.</p>
<pre class="verbatim">readInput t1 t2 = do inpStr1 &lt;- readFile t1

                     inpStr2 &lt;- readFile t2

                     let tmMap = getteamMap $ getList1 $ lines inpStr1

                     let t2 = getList2 (lines inpStr2)

                     return $ Tourney tmMap [] t2

getteamMap ts = M.fromList $ zip (map teamName ts) ts

getList1 strs = map (getTeam . L.words) strs

getList2 strs = map (getClashes . L.words) strs

getTeam (t1:t2:t3:[]) = Team t1 (read t2) (read t3)

getTeam _             = error "Invalid team"

getClashes (t1:t2:[]) = (t1,t2)

getClashes _          = error " invalid clash"</pre>
<p>Running the file with the following Points table (which is the latest not counting the ongoing <strong>Chennai Vs Mohali</strong> game) and trying out various<br />
teams, we can see that even KKR still has an outside chance of reaching the game:</p>
<pre class="verbatim">Delhi  10  0.158

Mumbai 7  0.516

Kolkata  3  -1.097

Chennai  9  1.36

Blore  8  -0.395

Mohali  8  -0.5

Hyd  10   0.152

Jaipur 11  0.05</pre>
<p>and the following schedule:</p>
<pre class="verbatim">Delhi Mumbai

Hyd Mohali

Chennai Jaipur

Kolkata Delhi

Blore Mumbai

Hyd Jaipur

Blore Kolkata

Mohali Mumbai

Hyd Delhi

Mumbai Jaipur

Chennai Blore

Mohali Delhi

Chennai Mumbai

Hyd Kolkata

Jaipur Delhi

Mohali Hyd

Chennai Kolkata

Delhi Blore

Chennai Mohali

Jaipur Kolkata

Hyd Blore

Mumbai Delhi</pre>
<p>and checking out the options for Kolkata, the program runs for about <strong>2</strong> full minutes and presents a scenario under which the beleagured team can reach the semis. Possibly there are others as well!<br />
If the future matches go as below</p>
<pre class="verbatim">Match ("Mumbai",2) ("Delhi",0),

Match ("Hyd",2) ("Blore",0),

Match ("Jaipur",0) ("Kolkata",2),

Match ("Chennai",2) ("Mohali",0),

Match ("Delhi",0) ("Blore",2),

Match ("Chennai",0) ("Kolkata",2),

Match ("Mohali",2) ("Hyd",0),

Match ("Jaipur",2) ("Delhi",0),

Match ("Hyd",0) ("Kolkata",2),

Match ("Chennai",2) ("Mumbai",0),

Match ("Mohali",2) ("Delhi",0),

Match ("Chennai",2) ("Blore",0),

Match ("Mumbai",2) ("Jaipur",0),

Match ("Hyd",2) ("Delhi",0),

Match ("Mohali",2) ("Mumbai",0),

Match ("Blore",0) ("Kolkata",2),

Match ("Hyd",2) ("Jaipur",0),

Match ("Blore",2) ("Mumbai",0),

Match ("Kolkata",2) ("Delhi",0),

Match ("Chennai",2) ("Jaipur",0),

Match ("Hyd",2) ("Mohali",0),

Match ("Delhi",2) ("Mumbai",0)</pre>
<p>the final points table would look like:</p>
<pre class="verbatim">Hyd -&gt; points  = 18, NetRunRate = 1.152

Chennai -&gt; points = 17, NetRunRate = 2.8600001

Mohali -&gt; points = 14, NetRunRate = 0.0 

Kolkata -&gt; points = 13, NetRunRate = 1.403

Jaipur -&gt; points = 13, NetRunRate = -1.45 

Blore -&gt; points = 12, NetRunRate = -0.895

Delhi -&gt; points = 12, NetRunRate = -2.342

Mumbai -&gt; points = 11, NetRunRate = -0.48400003</pre>
<p>So you see, The tournament is indeed wide open!</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kapilash.wordpress.com/29/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kapilash.wordpress.com/29/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kapilash.wordpress.com/29/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kapilash.wordpress.com/29/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kapilash.wordpress.com/29/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kapilash.wordpress.com/29/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kapilash.wordpress.com/29/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kapilash.wordpress.com/29/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kapilash.wordpress.com/29/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kapilash.wordpress.com/29/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kapilash.wordpress.com&blog=1696932&post=29&subd=kapilash&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://kapilash.wordpress.com/2009/05/07/are-the-knight-riders-totally-out-of-semis/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e5f6c043a7fc3e5a20d6df63b1fa70c4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kapilash</media:title>
		</media:content>
	</item>
		<item>
		<title>Sudoku Zipper</title>
		<link>http://kapilash.wordpress.com/2009/04/23/sudoku-zipper/</link>
		<comments>http://kapilash.wordpress.com/2009/04/23/sudoku-zipper/#comments</comments>
		<pubDate>Thu, 23 Apr 2009 10:35:10 +0000</pubDate>
		<dc:creator>kapilash</dc:creator>
				<category><![CDATA[haskell]]></category>

		<guid isPermaLink="false">http://kapilash.wordpress.com/?p=21</guid>
		<description><![CDATA[I will post about an interesting idiom in Functional Programming , that I came across recently &#8211; Zipper. zipper provides us with
the ability to traverse pure functional programming data structures with surprising agility and efficiency , without losing the purity.
module Main where

import Sudoku.Parser as P

import Sudoku.Data as D

import System.Environment(getArgs)

import Data.Tree

import Data.Tree.Zipper
The imports are similar to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kapilash.wordpress.com&blog=1696932&post=21&subd=kapilash&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>I will post about an interesting idiom in Functional Programming , that I came across recently &#8211; Zipper. zipper provides us with<br />
the ability to traverse pure functional programming data structures with surprising agility and efficiency , without losing the purity.</p>
<pre class="verbatim">module Main where

import Sudoku.Parser as P

import Sudoku.Data as D

import System.Environment(getArgs)

import Data.Tree

import Data.Tree.Zipper</pre>
<p>The imports are similar to the <a href="http://kapilash.wordpress.com/2009/04/22/lazy-evaluation/" target="_self">earlier one</a> but with an additional module loaded &#8211; the zipper.</p>
<p>There’s just a minor change in the <em>main</em>, we pass the sudoku to zipperSol, which solves the sudoku and prints the solution.</p>
<pre class="verbatim">main = do args &lt;- getArgs

          case args of

            (f:[])   -&gt; do x &lt;- parseSudokuFromFile f

                           zipperSol x

            _        -&gt; do usage

usage = do print "Usage:"

           print "STest &lt;file&gt;"</pre>
<p>We create the tree the way we did earlier.</p>
<pre class="verbatim">sudokuTree s = Node s (map sudokuTree (explore s))

explore s =  case (getUnfilledCell s) of

               Just (c,pos) -&gt; filter validSudoku [ (fillSudoku s pos val) |  val &lt;- getCells c ]

               Nothing      -&gt; []

getCells (Ttv  lst) = map Sld lst

getCells  x =     [x]</pre>
<p>Then, pass it on to the <em>fromTree</em> function of <strong>Data.Tree.Zipper</strong> module to get a zipper. Thus the below function takes a Sudoku and<br />
constructs a zipper out of it.</p>
<pre class="verbatim">sudokuZipper s = fromTree $ sudokuTree s</pre>
<p>Now the solution is using Depth First Search. Search for nodes in the tree in depth first manner and if a solution is found, print it and otherwise<br />
report inability.</p>
<pre class="verbatim">zipperSol s = case (dfs $ sudokuZipper s) of

                Nothing -&gt; do print "No solution found <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_sad.gif' alt=':-(' class='wp-smiley' />  "

                (Just x) -&gt;do print  x</pre>
<p>The function to perform depth first search is simple too. Given a treeLocation, we check if it is a leaf. If it is a leaf, we need to handle it differently.<br />
Otherwise, we call dfs on the first child of the tree in a recursive manner.<br />
The different handling of the leaf node is this: see, if it is a solution. If it is, report it. Otherwise, delete this leaf and perform the depth first<br />
search on the new tree formed.<br />
<strong>Data.Tree.Zipper.delete</strong> function returns a <em>May</em> <em>be</em> <em>TreeLoc</em>. The new location will be the right sibling of the treeLoc that we deleted or, if<br />
there’s no right sibling, the parent (which will become a leaf).<br />
it is a leaf node.</p>
<pre class="verbatim">dfs :: TreeLoc Sudoku -&gt; Maybe Sudoku

dfs treeLoc = case firstChild treeLoc of

                 Nothing  -&gt; handleLeafNode treeLoc

                 Just x   -&gt; dfs x

handleLeafNode treeLoc =

    case (solvedLoc treeLoc) of

      Just solution -&gt; Just solution

      Nothing -&gt;  case (delete treeLoc) of

                   Nothing -&gt; Nothing

                   (Just x) -&gt; dfs x

solvedLoc :: TreeLoc Sudoku -&gt; Maybe Sudoku

solvedLoc (Loc (Node x _) _ _ _) = if (hasEmptyCells x) then

                                      Nothing

                                   else (Just x)

hasEmptyCells s = case (getUnfilledCell s) of

                    Nothing  -&gt; False

                    Just _   -&gt; True</pre>
<p>Elegant and cool. This program is slightly slower than my earlier one ( it takes 9 seconds to solve a sudoku that was solved in 8 seconds by the<br />
earlier, tree based one) and the memory consumption is slightly on the higher side as well. However I can choose my search strategy.<br />
I would be able to move from depth first search to breadth first search or best first search without breaking a sweat.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kapilash.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kapilash.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kapilash.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kapilash.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kapilash.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kapilash.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kapilash.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kapilash.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kapilash.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kapilash.wordpress.com/21/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kapilash.wordpress.com&blog=1696932&post=21&subd=kapilash&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://kapilash.wordpress.com/2009/04/23/sudoku-zipper/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e5f6c043a7fc3e5a20d6df63b1fa70c4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kapilash</media:title>
		</media:content>
	</item>
		<item>
		<title>Lazy Evaluation</title>
		<link>http://kapilash.wordpress.com/2009/04/22/lazy-evaluation/</link>
		<comments>http://kapilash.wordpress.com/2009/04/22/lazy-evaluation/#comments</comments>
		<pubDate>Wed, 22 Apr 2009 21:37:36 +0000</pubDate>
		<dc:creator>kapilash</dc:creator>
				<category><![CDATA[haskell]]></category>

		<guid isPermaLink="false">http://kapilash.wordpress.com/?p=11</guid>
		<description><![CDATA[While I understood the idea of lazy evaluation for a while now, today I saw it in action for the first time. I intend to share
what I found in this post. In the process, I hope to make amends for the ridiculous code that I had posted earlier.  Much of the credit for improvement in [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kapilash.wordpress.com&blog=1696932&post=11&subd=kapilash&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>While I understood the idea of lazy evaluation for a while now, today I saw it in action for the first time. I intend to share<br />
what I found in this post. In the process, I hope to make amends for the ridiculous code that I had posted <a title="earlier post on sudoku solving" href="http://kapilash.wordpress.com/2008/05/11/monadic-combinators-for-sudoku/">earlier</a>.  Much of the credit for improvement in my <em>haskellfu</em> goes to  <a href="http://www.realworldhaskell.org" target="_blank">Real World Haskell</a> and to <a href="http://www.amazon.com/Haskell-School-Expression-Functional-Programming/dp/0521644089" target="_blank">Haskell School of Expression</a>.</p>
<p>The problem is a relatively simple one &#8211; to solve a sudoku.</p>
<p><!--TOC section Preliminaries--></p>
<h2 class="section"><!--SEC ANCHOR --><a name="htoc1">1</a> Preliminaries</h2>
<p><!--SEC END --></p>
<pre class="verbatim">module Main where

import Sudoku.Parser as P
import Sudoku.Data as D
import System.Environment(getArgs)
import Data.Tree</pre>
<p>Out of the above imports, Sudoku.Parser is an un-important module whose responsibility is to parse a given text file containing<br />
the input sudoku and to create a <strong>Sudoku</strong> data structure, which is defined in the next module in the list &#8211; the <em>Sudoku.Data</em>.<br />
Apart from defining the data , the Data module also exports the functions needed to manipulate the in-memory representation of the sudoku.<br />
These two modules are not really relevant for this post. That is, the current algorithm is “independant” of the way the <em>Sudoku</em> is<br />
represented in memory.</p>
<p>However, in order to give the context, (especially for the later sections where I present the profiling data),<br />
I’ve used an Array of <strong>Cell</strong>s and an integer representing the <em>unit</em> of the Sudoku. So a normal,  9 <em>X</em> 9  , sudoku will be an <strong>Array</strong><br />
of (<em>Int</em>,<em>Int</em>) ranging from (0,0) to  (80,80)  and the unit is 3 to indicate the size of the array. (The same representation can deal<br />
with a 16 <em>X</em> 16 or a 25 <em>X</em> 25 or higher sudoku as well ( although &#8211; I could not find test data to try it).<br />
And a cell is defined somewhat like below:</p>
<pre class="verbatim">data Cell = Given Int
            | ONEOF [Int]
            | Sld Int</pre>
<p>An empty Cell will be represented as a list of the values it can take. Given cell is represented as an Int. In order to perform trial and error,<br />
the cell with a list will be replaced by a <em>Sld n</em> where n is a number taken from ONEOF’s list.</p>
<p>Going back to the imports,<br />
<em>System.Environment</em> is imported for accessing the name of the file from command line arguments.<br />
The next one that was imported &#8211; <strong>Data.Tree</strong>, is a part of the standard Haskell libraries and forms the crux of this algorithm.<br />
It provides a (lazy) tree data type and related functions.</p>
<p><!--TOC section Data.Tree--></p>
<h2 class="section"><!--SEC ANCHOR --><a name="htoc2">2</a> Data.Tree</h2>
<p><!--SEC END --></p>
<p>The tree is defined as</p>
<pre class="verbatim">data Tree a = Node { rootLabel :: a, subForest :: Forest}</pre>
<p>where, Forest is a synonym for a list of <em>Tree</em>s.</p>
<p>The brute-force approach to solve the problem is to create a (lazy) tree of sudokus, such that the given tree is at the root. The children of a given node,<br />
(that is, the <em>subForest</em> of the <em>Tree</em>) are generated by taking one of the unfilled cell in the sudoku of the node , and substituting with one of the possible<br />
values that this cell can take. In other words, each child of a node represents a trial for a particular cell in the sudoku.<br />
However, we ensure that the sudokus at each node are “well-formed” sudokus, which follow the rules of the sudoku. Consequently, we have , at the leaves,<br />
either a solved sudoku or a wrong choice that’s been taken.</p>
<p>The creation of such a tree is surprisingly pithy</p>
<pre class="verbatim">sudokuTree s = Node s (map sudokuTree (explode s))

explode s =  case (getUnfilledCell s) of
               Just (c,pos) -&gt; filter validSudoku
                          [ (fillSudoku s pos val) |  val &lt;- getCells c ]
               Nothing      -&gt; []</pre>
<p>As can be seen from the use of <em>filter</em>, we are ensuring that only valid Sudokus can form the subforest of a node.<br />
And the process is repeated recursively.</p>
<p>A side note on the functions from <em>Sudoku.Data</em> module:</p>
<ol class="enumerate" type="1">
<li class="li-enumerate"> The <em>getUnfilledCell</em> returns <em>Maybe</em> (<em>Cell</em>,(<em>Int</em>,<em>Int</em>)) that, is a cell and its position if there are empty cells , nothing otherwise.</li>
<li class="li-enumerate"><em>validSudoku</em> is a function which takes a sudoku and returns false if it breaks any of the rules of sudoku , true otherwise.</li>
</ol>
<p>Since we are interested mainly in the leaves of the tree, we now define</p>
<pre class="verbatim">getLeaves (Node a []) = [a]
getLeaves (Node a xs) = concatMap getLeaves xs</pre>
<p>which is again a simple straight forward function.</p>
<p>Thats it. The things left are the main function and a couple of helper functions.<br />
The main function has to perform the following actions:</p>
<ol class="enumerate" type="1">
<li class="li-enumerate"> reading the file name from the command line argument</li>
<li class="li-enumerate">passing the file name to a parser combinator that parses the file and returns a sudoku</li>
<li class="li-enumerate">creating a tree using this sudoku, and from the leaves of which, filtering out those sudokus that are filled</li>
<li class="li-enumerate">printing the list of such sudokus.</li>
</ol>
<pre class="verbatim">main = do args &lt;- getArgs
          case args of
            (f:[])   -&gt; do x &lt;- parseSudokuFromFile f
                           print  $ filter
                                  (\x -&gt; not $ hasEmptyCells x)
                                  (getLeaves $ sudokuTree x)
            _        -&gt; do usage

usage = do print "Usage:"
           print "STest &lt;file&gt;"

getCells (Ttv  lst) = map Sld lst
getCells  x =     [x]

hasEmptyCells s = case (getUnfilledCell s) of
                    Nothing  -&gt; False
                    Just _   -&gt; True</pre>
<p><!--TOC section Running the code--></p>
<h2 class="section"><!--SEC ANCHOR --><a name="htoc3">3</a> Running the code</h2>
<p><!--SEC END --></p>
<p>I compiled the code with  −<em>O</em>2  option (ghc) and then ran the code with  −<em>S</em> option on a few puzzles from WebSudoku.<br />
I here present some interesting data related to one of the puzzle for which it took 19 seconds to solve (the only one that took more than 5<br />
seconds to solve).<br />
The problem is as below (it is an <em>evil</em> category puzzle taken from the same site).</p>
<pre class="verbatim">805000000
920000007
000650090
400810020
000204000
060079005
070086000
500000069
000000402</pre>
<p>here 0 represents a space. The output was as follows:</p>
<pre class="verbatim">:~/src/hascode&gt; time ./SudokuTree Test/Sudoku/test3
"Parsed Sudoku"
[8,3,5,7,9,2,6,1,4
9,2,6,1,4,8,5,3,7
7,4,1,6,5,3,2,9,8
4,9,7,8,1,5,3,2,6
3,5,8,2,6,4,9,7,1
1,6,2,3,7,9,8,4,5
2,7,4,9,8,6,1,5,3
5,8,3,4,2,1,7,6,9
6,1,9,5,3,7,4,8,2
]

real    0m19.607s
user    0m19.589s
sys     0m0.016s</pre>
<p>and when I ran it with the  −<em>S</em> option of RTS, it contained the following astonishing data:</p>
<pre class="verbatim">   5,488,579,640 bytes allocated in the heap
      49,910,436 bytes copied during GC
          45,804 bytes maximum residency (39 sample(s))
          66,900 bytes maximum slop
               2 MB total memory in use (0 MB lost due to fragmentation)

  Generation 0: 10449 collections,     0 parallel,  0.35s,  0.42s elapsed
  Generation 1:    39 collections,     0 parallel,  0.00s,  0.01s elapsed

  INIT  time    0.00s  (  0.00s elapsed)
  MUT   time   17.74s  ( 17.94s elapsed)
  GC    time    0.35s  (  0.42s elapsed)
  EXIT  time    0.00s  (  0.00s elapsed)
  Total time   18.09s  ( 18.37s elapsed)

  %GC time       1.9%  (2.3% elapsed)

  Alloc rate    309,370,701 bytes per MUT second

  Productivity  98.0% of total user, 96.6% of total elapsed</pre>
<p>The number of bytes allocated seemed staggering! Incidentally, I computed the number of nodes in the tree, using the <strong>Data.Tree.flatten</strong> function<br />
and for the above problem, it is 68480! That is, <strong>68480</strong> sudokus &#8211; each of which has 9 <em>X</em> 9 <em>Cells</em> !<br />
It ofcourse is lazy evaluation (and the garbage collection), in action &#8211; At no point in time, the whole tree is in memory. Only the portion of the<br />
tree that is needed is built and the other nodes are not (yet) evaluated. And ofcourse those nodes that are not needed anymore<br />
are garbage collected.<br />
A further proof of the impact of lazy evaluation comes when I modify the program such that it prints the first solution that it finds (that is, we stop<br />
when we get the first solution). I do it by modifying only the main function</p>
<pre class="verbatim">main = do args &lt;- getArgs
          case args of
            (f:[])   -&gt; do x &lt;- parseSudokuFromFile f
                           print  $ filter
                                  (\x -&gt; not $ hasEmptyCells x)
                                  (getLeaves $ sudokuTree x)
            _        -&gt; do usage</pre>
<p>to</p>
<pre class="verbatim">main = do args &lt;- getArgs
          case args of
            (f:[])   -&gt; do x &lt;- parseSudokuFromFile f
                           print $ head  $ filter
                                  (\x -&gt; not $ hasEmptyCells x)
                                  (getLeaves $ sudokuTree x)
            _        -&gt; do usage</pre>
<p>That is, I did not change the way the tree is constructed nor did I interfere in the recursive function (In imperative-speak, I did not add a “break”<br />
statement), I am only printing the first member of the list and ignoring the rest (where present).</p>
<p>And this time, the same sudoku is solved under 8 seconds, which is relatively unsurprising,<br />
but the profiling data (from  − <em>S</em> RTS option) provided me with the shock of the day</p>
<pre class="verbatim">   2,565,699,092 bytes allocated in the heap
      23,344,784 bytes copied during GC
          40,828 bytes maximum residency (19 sample(s))
          62,928 bytes maximum slop
               2 MB total memory in use (0 MB lost due to fragmentation)

  Generation 0:  4884 collections,     0 parallel,  0.21s,  0.20s elapsed
  Generation 1:    19 collections,     0 parallel,  0.00s,  0.00s elapsed

  INIT  time    0.00s  (  0.00s elapsed)
  MUT   time    8.74s  (  8.84s elapsed)
  GC    time    0.21s  (  0.21s elapsed)
  EXIT  time    0.00s  (  0.00s elapsed)
  Total time    8.95s  (  9.05s elapsed)

  %GC time       2.3%  (2.3% elapsed)

  Alloc rate    293,539,944 bytes per MUT second

  Productivity  97.7% of total user, 96.6% of total elapsed</pre>
<p>Perhaps it does not need an expert of such matters to say that in the second case the portion of the tree that was evaluated was only about a half of the<br />
earlier.( Going by the figures under the sections related to GC like “bytes copied during GC” and the number of “collections”).</p>
<p>Although what I said here may not be new for most haskellers, it still gives me goose bumps thinking of the way evaluation must have happened and how<br />
different it is from what I am used to.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kapilash.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kapilash.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kapilash.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kapilash.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kapilash.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kapilash.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kapilash.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kapilash.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kapilash.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kapilash.wordpress.com/11/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kapilash.wordpress.com&blog=1696932&post=11&subd=kapilash&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://kapilash.wordpress.com/2009/04/22/lazy-evaluation/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e5f6c043a7fc3e5a20d6df63b1fa70c4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kapilash</media:title>
		</media:content>
	</item>
		<item>
		<title>Snowflake fractal</title>
		<link>http://kapilash.wordpress.com/2008/05/16/snowflake-fractal/</link>
		<comments>http://kapilash.wordpress.com/2008/05/16/snowflake-fractal/#comments</comments>
		<pubDate>Fri, 16 May 2008 16:44:48 +0000</pubDate>
		<dc:creator>kapilash</dc:creator>
				<category><![CDATA[haskell]]></category>

		<guid isPermaLink="false">http://kapilash.wordpress.com/?p=9</guid>
		<description><![CDATA[In this article, I will write a haskell program that displays a snowflake haskell. This is given as a problem in one of the best books on Haskell &#8211; The Haskell School of Expression, by Proffessor Paul Hudak. One can see a sample snowflake here on the math forum.
I am using a haskell package called [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kapilash.wordpress.com&blog=1696932&post=9&subd=kapilash&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><span style="color:blue;">In this article, I will write a haskell program that displays a snowflake haskell. This is given as a problem in one of the best books on Haskell &#8211; <a title="The Haskell School of Expression" href="http://www.amazon.com/Haskell-School-Expression-Functional-Programming/dp/0521644089">The Haskell School of Expression</a>, by <a title="Proffessor Paul Hudak" href="http://cs-www.cs.yale.edu/homes/hudak.html">Proffessor Paul Hudak</a>. One can see a sample snowflake <a title="here" href="http://mathforum.org/~sanders/mathart/images/Koch.gif" target="_blank">here </a>on the math forum.<br />
I am using a haskell package called gtk2hs ,which contains a special module needed for the code of that book.<br />
</span></p>
<pre>module Snowflake where

import Graphics.SOE.Gtk
</pre>
<p><!--TOC section Setting the stage--></p>
<h2 class="section"><!--SEC ANCHOR --><a name="htoc1">1</a> Setting the stage</h2>
<p><!--SEC END --></p>
<p><span style="color:blue;">I will start with a “command” (haskell expressions/functions that yield actions when they are applied) that is given in the book.<br />
This command takes a window as an input and waits for the user to press the space bar. Once it is pressed, it will close the window.<br />
This is used in a very elegant piece of code that displays <a title="Sierpinski's triangle" href="http://math.rice.edu/~lanius/fractals/s0.gif" target="_blank">Sierpinski’s triangle</a><br />
</span></p>
<pre>spaceClose :: Window -&gt; IO ()
spaceClose w
    = do k&lt;- getKey w
         if k == ' ' then closeWindow w
                     else spaceClose w</pre>
<p><span style="color:blue;">Now a function that limits the size of the smallest ’star’.An example for how to define global constants in haskell</span></p>
<pre>minSize :: Int
minSize = 8</pre>
<p><!--TOC section Recursive star--></p>
<h2 class="section"><!--SEC ANCHOR --><a name="htoc2">2</a> Recursive star</h2>
<p><!--SEC END --></p>
<p><span style="color:blue;">The idea is to draw a Star of David &#8211; by overlapping two equilateral triangles such that<br />
their circum-centers coincide. Now, in this Graphics module that I am using, one can draw a polygon by invoking a </span><span style="color:blue;"><strong>polygon</strong></span><span style="color:blue;"> command with a list of x-y co-ordinates.<br />
But due to some sort of quirkiness with the definition of polygon this module, it is necessary that the last element in the list is the same as the first pair of co-ordinates.<br />
Hence, in order to draw a triangle, I will have to invoke the </span><span style="color:blue;"><strong>polygon</strong></span><span style="color:blue;"> command using a list containing 4 co-ordinates.<br />
So, I will define my data type as a record containing 2 sets of lists (one for each triangle) and also a size.</span></p>
<pre>data StarOfDavid = SoD {trA :: [(Int,Int)],trB ::[(Int,Int)],szSoD::Int}
</pre>
<p><span style="color:blue;">That done, I now need a function which takes a pair of x,y co-ordinates and the size (that is the radius of the circum-circle) and give me<br />
This function is based on elementary trignometry and is pretty straight forward.<br />
the StarOfDavid</span></p>
<pre>getVertices :: (Int,Int) -&gt;Int -&gt; StarOfDavid
getVertices (x,y) r = SoD {trA = [(x,y-r), (x - (mulCos30 r), y + r `div` 2),(x + (mulCos30 r), y + r `div` 2 ),(x,y-r)],
                           trB = [(x,y+r),(x - (mulCos30 r), y - r `div` 2),(x + (mulCos30 r), y - r `div` 2),(x,y+r)],
                           szSoD = r}

mulCos30 ::Int -&gt; Int
mulCos30 x = round ( (fromIntegral x) * 0.866 )
</pre>
<p><span style="color:blue;"><br />
Now I need a command that takes a Window and a record corresponding to StarOfDavid, and draw it on the window, if and only if, the size is greater than the minSize defined earlier. Also, since the fractal can be drawn by drawing six stars at one-third the size at each of the six ‘corners’ of the Star and repeating the process till we reach the minimum size.<br />
To implement all that in haskell is simple and  elegant as below.</span></p>
<pre>drawStarOfDavid :: Window -&gt; StarOfDavid -&gt; Color -&gt; IO()
drawStarOfDavid w sod c =
 if (szSoD sod) &lt;= minSize then return ()
 else do drawInWindow w (withColor c (polygon (trA sod)))
         drawInWindow w (withColor c (polygon (trB sod)))
         sequence_ (map (\x-&gt; drawStarOfDavid w x c) (nextStarCenters sod))

nextCenters :: StarOfDavid -&gt; [(Int,Int)]
nextCenters dos = (take 3 (trA dos) ) ++ (take 3 (trB dos))

nextStarCenters :: StarOfDavid -&gt; [StarOfDavid]
nextStarCenters dos = map (\x-&gt; getVertices x newsiz ) (nextCenters dos)
                        where newsiz = div (szSoD dos) 3
</pre>
<p><!--TOC section The main method--></p>
<h2 class="section"><!--SEC ANCHOR --><a name="htoc3">3</a> The main method</h2>
<p><!--SEC END --></p>
<p><span style="color:blue;">Finally, the main method, a command that invokes the drawStarOfDavid command</span>.</p>
<pre>main
 = runGraphics (
     do w &lt;- openWindow
            "Snowflake Fractal" (400,400)
        drawStarOfDavid w (getVertices (250,250) 150)  Cyan
        spaceClose w
   )</pre>
<p><span style="color:blue;"><br />
That’s it. Of course the picture that is generated is mono-chromatic and not as colorful as the math-forum one that I linked earlier.<br />
(Also, the site has been generated using latex and hevea).<br />
</span><a href="http://kapilash.files.wordpress.com/2008/05/snowflake_fractal.png"><img src="http://kapilash.files.wordpress.com/2008/05/snowflake_fractal.png?w=300&#038;h=210" alt="Snowflake Fractal" width="300" height="210" class="alignnone size-medium wp-image-10" /></a></p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/kapilash.wordpress.com/9/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/kapilash.wordpress.com/9/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kapilash.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kapilash.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kapilash.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kapilash.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kapilash.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kapilash.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kapilash.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kapilash.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kapilash.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kapilash.wordpress.com/9/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kapilash.wordpress.com&blog=1696932&post=9&subd=kapilash&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://kapilash.wordpress.com/2008/05/16/snowflake-fractal/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e5f6c043a7fc3e5a20d6df63b1fa70c4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kapilash</media:title>
		</media:content>

		<media:content url="http://kapilash.files.wordpress.com/2008/05/snowflake_fractal.png?w=300" medium="image">
			<media:title type="html">Snowflake Fractal</media:title>
		</media:content>
	</item>
		<item>
		<title>Monadic combinators for Sudoku</title>
		<link>http://kapilash.wordpress.com/2008/05/11/monadic-combinators-for-sudoku/</link>
		<comments>http://kapilash.wordpress.com/2008/05/11/monadic-combinators-for-sudoku/#comments</comments>
		<pubDate>Sun, 11 May 2008 08:46:43 +0000</pubDate>
		<dc:creator>kapilash</dc:creator>
				<category><![CDATA[haskell]]></category>

		<guid isPermaLink="false">http://kapilash.wordpress.com/?p=8</guid>
		<description><![CDATA[In this blog, I try to get a few monadic combinators to solve Sudokus and see if they can get any better than what I got earlier.  Again, the focus is very narrow &#8211; only to understand monads.
I am too lazy to start afresh. , along with the array module, I will also import the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kapilash.wordpress.com&blog=1696932&post=8&subd=kapilash&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>In this blog, I try to get a few monadic combinators to solve Sudokus and see if they can get any better than what I got earlier.  Again, the focus is very narrow &#8211; only to understand monads.</p>
<p>I am too lazy to start afresh. , along with the array module, I will also import the Sudoku module that I defined earlier.<br />
And of course I will have to include the Monad module.</p>
<pre><span style="font-size:x-small;">module MonSudoku where</span>

<span style="font-size:x-small;">import Data.Array
import Sudoku
import Control.Monad
</span></pre>
<p>Now I will define a new data type called State to hold the array and the current position.<br />
But I will define it as a generic record that can hold any pair of data structure and position combination. Ideally, I should also<br />
store the access method (for example the ‘!’ operator in case of an array, and a ‘!!’ in case of list). But I will pass it one for<br />
now. The focus of the blog is very narrow &#8211; to be able to implement a non-trivial instance of monad.<br />
Coming back to the data types, I will define a new type called GenericSolver using the newtype construction.<br />
This ‘newtype’ defines a new container for all the functions that take a given state and returns a list of triplets.<br />
We will see later, what the triplet is composed of.<br />
Also, I will define a ‘type’ called “Solver a” that has <em>Sudoku</em> as the data structure and (<em>row</em>,<em>col</em>)  as the position.</p>
<pre><span style="font-size:x-small;">type Solver a = GenSolver Sudoku (Int,Int) a</span>

<span style="font-size:x-small;">newtype GenSolver ds pos a = Solver ( State ds pos -&gt; [(a,pos,ds)] )</span>

<span style="font-size:x-small;">data State ds pos = State {
       dataStruct :: ds,
       thePosition :: pos
     }</span></pre>
<p><!--TOC section The first monad--></p>
<h2 class="section"><!--SEC ANCHOR --><a name="htoc1">1</a> The first monad</h2>
<p><!--SEC END --></p>
<p>Now I will define two functions &#8211; <em>solveReturn</em> and <em>SolveBind</em> so as to make <em>GenSolver ds pos</em> an instance of <em>Monad</em>.<br />
The very purpose of this blog (and ,in fact, for this approach for solving Sudokus) is creation of an instance of <em>Monad</em>.</p>
<pre><span style="font-size:x-small;">solveReturn  :: a -&gt; GenSolver ds pos a
solveReturn x
    = Solver (\state -&gt;[(x,(thePosition state),(dataStruct state))] )</span>

<span style="font-size:x-small;">solveBind :: GenSolver ds pos a -&gt; (a -&gt; GenSolver ds pos b) -&gt; GenSolver ds pos b
solveBind (Solver s) f
   = Solver (\state -&gt;
      concat ( solveBind' (s state) f )
            )</span>

<span style="font-size:x-small;">solveBind' :: [(a,pos,ds)] -&gt;(a -&gt; GenSolver ds pos b)-&gt;[[(b,pos,ds)]]
solveBind' []   f            = []
solveBind' ((a,pos,ds):xs) f  =  ((f2 (State ds pos)):(solveBind' xs f))
                                where Solver f2 = f a</span></pre>
<p>Now, I can proudly define the <em>GenSolver</em> as an instance of Monad using:</p>
<pre><span style="font-size:x-small;">instance Monad (GenSolver ds pos) where
  return x   = solveReturn x
  p &gt;&gt;= f    = solveBind p f
</span></pre>
<p>Now that I have my monad, I will be able to use the <em>do</em> notation.</p>
<p><!--TOC section Primitive solvers--></p>
<h2 class="section"><!--SEC ANCHOR --><a name="htoc2">2</a> Primitive solvers</h2>
<p><!--SEC END --></p>
<p>A few primitive functions first.</p>
<p><!--TOC subsection Item solver--></p>
<h3 class="subsection"><!--SEC ANCHOR --><a name="htoc3">2.1</a> Item solver</h3>
<p><!--SEC END --></p>
<p>Item solver takes a Sudoku and a position and gives a new sudoku such that :</p>
<ol class="enumerate" type="1">
<li class="li-enumerate"> if the cell at the position is filled, then returns the same Sudoku with an empty list</li>
<li class="li-enumerate">if the cell is not filled, it provides a list of all the possible values that cell can take</li>
</ol>
<p>As of now, I am not sure if there can be a solver which is more primitive than this &#8211; that which I can use to define this.<br />
But that is beside the point.</p>
<pre><span style="font-size:x-small;">item :: Solver [Int]
item = Solver ( \state -&gt;
                     let
                           sudoku = dataStruct state
                           pos    = thePosition state
                      in
                      case ( sudoku ! pos) of
                            FilledCell v -&gt; [([v],pos, sudoku)]
                            EmptyCell (x:xs) -&gt; [((x:xs),pos,sudoku)]
                            EmptyCell []  -&gt; []
               )</span></pre>
<p><!--TOC subsection Propogator--></p>
<h3 class="subsection"><!--SEC ANCHOR --><a name="htoc4">2.2</a> Propogator</h3>
<p><!--SEC END --></p>
<p>I will need a function that can be <em>bound</em> to the <em>item</em> solver. That is, a function of type</p>
<pre> [Int]-&gt;Solver ()</pre>
<p>To help me out in that I will first write a function that takes an Int first</p>
<pre><span style="font-size:x-small;">
prop1 :: Int-&gt;Solver ()
prop1 x = Solver (\state -&gt;
                            let
                               sudoku = dataStruct state
                               pos    = thePosition state
                               sudoku' = sudoku // [(pos,FilledCell x)]
                            in
                             [((),pos,sudoku')]
                 )</span>

<span style="font-size:x-small;">propogate :: [Int] -&gt;Solver()
propogate  []      = Solver (\state -&gt; [])
propogate  [h]     = prop1 h
propogate  (x:xs)  = Solver (\state-&gt;
                            let
                              Solver f1 = prop1 x
                              Solver frest = propogate xs
                            in
                              (f1 state)  ++ (frest state)
                            )</span></pre>
<p>There now, I have most things that I need.<br />
Firstly, I have an “item” function that given a Sudoku and an unfilled position, gives me a list of values that position can take.<br />
Secondly, I have a function ‘propogate’ that can take a list of values for a Sudoku-position pair and gives me a list<br />
of Sudokus such that each of them have the same same position updated with one of the values of the list.<br />
Then, one of the sudokus from this list should lead me to the solution.<br />
Thirdly, by virtue of the fact that the “Solver” is an instance of Monad, I should be able to use the “do” notation.</p>
<p><!--TOC section New Algorithm--></p>
<h2 class="section"><!--SEC ANCHOR --><a name="htoc5">3</a> New Algorithm</h2>
<p><!--SEC END --></p>
<p>It is now easy to imagine a small enhancement to the naive algorithm for solving sudokus:</p>
<ol class="enumerate" type="1">
<li class="li-enumerate"> Apply the naive algorithm on a given Sudoku.</li>
<li class="li-enumerate">Check if the Sudoku is filled. If filled, that is the answer. Stop</li>
<li class="li-enumerate">Find the position of the cell containing only two possible values.</li>
<li class="li-enumerate">If there is no such a position, return an empty list. Either it is a wrong “thread” or I am up against some devilishly evil puzzle<br />
that I cannot solve.</li>
<li class="li-enumerate">Apply the <em>item</em> function on the Sudoku at the position gives me a list of possible values for that position.</li>
<li class="li-enumerate">Using <em>propogate</em>, we get two sudokus, each of which takes one of the possible values at that position.</li>
<li class="li-enumerate">Take one of these sudokus and go to step 3. If it returns a Sudoku, then it is the answer. Stop.<br />
If it returns an empty list, then try the next one.</li>
<li class="li-enumerate">If I have no more sudokus to try, raise your hands</li>
</ol>
<p><!--TOC subsection A few more primitives--></p>
<h3 class="subsection"><!--SEC ANCHOR --><a name="htoc6">3.1</a> A few more primitives</h3>
<p><!--SEC END --></p>
<p>For the sake of simplicity, let me call the cell that can have only two possible values in an unfilled Sudoku as a “forker”.<br />
I now need a function to get a forker. I will also write a small wrapper over loopTillDone that applies the naive algorithm as<br />
best as possible.</p>
<pre><span style="font-size:x-small;">getNextForker :: Sudoku-&gt;(Int,Int) -&gt; (Int,Int)
getNextForker _ (9,0) = error "NoSuchCell"
getNextForker sudoku (row,col) = let
                                      nextCol = mod (col + 1) 9
                                      nextRow = if (nextCol == 0 ) then row + 1 else row
                                 in
                                    case (sudoku ! (row,col) ) of
                                      FilledCell v -&gt; getNextForker sudoku (nextRow,nextCol)
                                      EmptyCell l  -&gt; if ( (length l) == 2) then (row,col)
                                                      else getNextForker sudoku (nextRow,nextCol)</span>

<span style="font-size:x-small;">naiveAlgo :: Sudoku -&gt; (Bool,Sudoku)
naiveAlgo sudoku = let
                    sudoku' = loopTillDone sudoku
                   in
                       ( not (hasEmptyCells sudoku' (0,0)),sudoku')</span>

<span style="font-size:x-small;">naSolves :: a -&gt; Solver Bool
naSolves    x         = Solver (\state -&gt;
                                  let
                                     sudoku = dataStruct state
                                     pos    = thePosition state
                                     (yOrN,sudoku') = naiveAlgo sudoku
                                  in
                                   [(yOrN , pos, sudoku')]
                               )</span>

<span style="font-size:x-small;">resetPos :: a -&gt; Solver ()
resetPos x = Solver (\state -&gt;
                          let
                            sudoku = dataStruct state
                            pos = getNextForker sudoku (0,0)
                          in
                            [( (),pos,sudoku)]
                    )</span></pre>
<p>The function naSolves and resetPos are Solvers that ignore the input. naSolves checks if any of the Sudoku has already been solved.<br />
resetPos updates the state so that the position is pointing to the next forker.</p>
<p><!--TOC section Combinators--></p>
<h2 class="section"><!--SEC ANCHOR --><a name="htoc7">4</a> Combinators</h2>
<p><!--SEC END --></p>
<p>I am now all set to write a few combinators.<br />
Let me <em>imaginatively</em> name the combinators as oneRound, twoRounds.threeRounds and fourRounds<br />
As their corny names suggest, they apply the enhanced algorithm once, twice ,thrice and four times respectively.<br />
They are as below:</p>
<pre><span style="font-size:x-small;">oneRound  :: Solver Bool
oneRound              = do{
                             x &lt;- item;
                             y &lt;- propogate x;
                             v &lt;- naSolves y;
                             return v
                          }</span>

<span style="font-size:x-small;">twoRounds  :: Solver Bool
twoRounds             = do{
                             v &lt;- oneRound;
                             if v then
                                 return v
                             else
                                do
                                  resetPos v;
                                  v' &lt;- oneRound;
                                  return v'
                          }</span>

<span style="font-size:x-small;">threeRounds ::Solver ()
threeRounds            = do{
                             v &lt;- oneRound;
                             if v then
                                 return ()
                             else
                                do
                                  resetPos v;
                                  twoRounds;
                                  return ();
                           }</span>

<span style="font-size:x-small;">fourRounds :: Solver Bool
fourRounds         = do{
                             v &lt;- twoRounds;
                             if v then
                                 return v
                             else
                                do
                                  resetPos v;
                                  v' &lt;-twoRounds;
                                  return v';
                         }</span>

<span style="font-size:x-small;">eightRounds :: Solver Bool
eightRounds         = do{
                             v &lt;- fourRounds;
                             if v then
                                 return v
                             else
                                do
                                  resetPos v;
                                  v' &lt;-fourRounds;
                                  return v';
                         }</span></pre>
<p><!--TOC section Testing them out--></p>
<h2 class="section"><!--SEC ANCHOR --><a name="htoc8">5</a> Testing them out</h2>
<p><!--SEC END --></p>
<p>Now a function that takes the input as a list (list of list of Ints) and runs one of the combinators and returns the Sudoku</p>
<p><!--TOC subsection To apply the combinators--></p>
<h3 class="subsection"><!--SEC ANCHOR --><a name="htoc9">5.1</a> To apply the combinators</h3>
<p><!--SEC END --></p>
<pre><span style="font-size:x-small;">scanListForFilled :: [(a,b,Sudoku)]-&gt; Int -&gt; Int
scanListForFilled [] pos = pos
scanListForFilled ((_,_,sudoku):xs) pos = if (hasEmptyCells sudoku (0,0))  then scanListForFilled xs (pos + 1)
                                          else  pos</span>

<span style="font-size:x-small;">runThreeRound :: [Int] -&gt; IO()
runThreeRound list = let
                        sudoku1             = fromList list (0,0) getInitSudoku
                        (p,sudNaive)        = naiveAlgo sudoku1
                        Solver solverFun    = threeRounds
                     in
                     if p then
                         do {
                             print sudNaive;
                             return ()
                            }
                     else
                       let
                         x = solverFun (State sudNaive (getNextForker sudNaive (0::Int,0::Int)) )
                         pos = scanListForFilled x (0)
                         (_,_,endSud) = x !! pos
                       in
                         do{
                            print $ showSudoku endSud;
                            print endSud;
                            return ()
                           }</span>

<span style="font-size:x-small;">runEightRound :: [Int] -&gt; IO()
runEightRound list = let
                        sudoku1             = fromList list (0,0) getInitSudoku
                        (p,sudNaive)        = naiveAlgo sudoku1
                        Solver solverFun    = eightRounds
                     in
                     if p then
                         do {
                             print sudNaive;
                             return ()
                            }
                     else
                       let
                         x = solverFun (State sudNaive (getNextForker sudNaive (0::Int,0::Int)) )
                         pos = scanListForFilled x (0)
                         (_,_,endSud) = x !! pos
                       in
                         do{
                            print $ showSudoku endSud;
                            print endSud;
                            return ()
                           }</span>

<span style="font-size:x-small;">runFourRound :: [Int] -&gt; IO()
runFourRound list = let
                        sudoku1             = fromList list (0,0) getInitSudoku
                        (p,sudNaive)        = naiveAlgo sudoku1
                        Solver solverFun    = fourRounds
                     in
                     if p then
                         do {
                             print sudNaive;
                             return ()
                            }
                     else
                       let
                         x = solverFun (State sudNaive (getNextForker sudNaive (0::Int,0::Int)) )
                         pos = scanListForFilled x (0)
                         (_,_,endSud) = x !! pos
                       in
                         do{
                            print $ showSudoku endSud;
                            print endSud;
                            return ()
                           }</span></pre>
<p><!--TOC subsection Testdata--></p>
<h3 class="subsection"><!--SEC ANCHOR --><a name="htoc10">5.2</a> Testdata</h3>
<p><!--SEC END --></p>
<p>A few sample puzzles from websudoku.com</p>
<pre><span style="font-size:x-small;">hard1 ::[[Int]]
hard1 = [[0, 2, 9, 0, 7, 0, 0, 0, 6],
         [0, 0, 0, 0, 0, 1, 9, 8, 0],
         [0, 0, 0, 9, 0, 8, 0, 0, 0],
         [0, 0, 0, 5, 0, 0, 0, 7, 4],
         [5, 0, 0, 0, 0, 0, 0, 0, 1],
         [4, 7, 0, 0, 0, 2, 0, 0, 0],
         [0, 0, 0, 3, 0, 9, 0, 0, 0],
         [0, 3, 5, 1, 0, 0, 0, 0, 0],
         [6, 0, 0, 0, 4, 0, 5, 2, 0]]</span>

<span style="font-size:x-small;">hard2 :: [[Int]]
hard2 = [[0,4,8,0,0,6,0,0,0],
         [6,0,0,0,8,0,3,0,1],
         [0,0,0,0,0,0,0,6,0],
         [0,1,0,6,0,3,5,0,0],
         [5,0,0,0,0,0,0,0,6],
         [0,0,7,4,0,2,0,9,0],
         [0,8,0,0,0,0,0,0,0],
         [2,0,5,0,7,0,0,0,4],
         [0,0,0,2,0,0,8,5,0]]</span>

<span style="font-size:x-small;">evil1 ::[[Int]]
evil1 = [[0, 0, 0, 0, 9, 4, 0, 8, 3],
         [0, 0, 0, 0, 0, 0, 0, 0, 0],
         [0, 8, 6, 7, 0, 0, 0, 2, 0],
         [1, 3, 2, 0, 0, 0, 6, 0, 0],
         [0, 0, 9, 0, 0, 0, 3, 0, 0],
         [0, 0, 4, 0, 0, 0, 9, 5, 8],
         [0, 4, 0, 0, 0, 2, 5, 3, 0],
         [0, 0, 0, 0, 0, 0, 0, 0, 0],
         [5, 9, 0, 8, 4, 0, 0, 0, 0]]</span>

<span style="font-size:x-small;">evil2 :: [[Int]]
evil2 = [[0,0,4,0,3,0,0,8,0],
         [0,0,0,8,0,0,4,0,0],
         [0,0,7,0,0,1,0,0,6],
         [0,7,8,0,0,0,0,5,9],
         [9,0,0,0,0,0,0,0,2],
         [2,4,0,0,0,0,1,3,0],
         [3,0,0,6,0,0,5,0,0],
         [0,0,9,0,0,2,0,0,0],
         [0,8,0,0,7,0,9,0,0]]</span></pre>
<p>It did manage to give a correct answer for evil1 above and also the evil puzzle that I used in the earlier blog.<br />
However It gave a wrong answer (containing two 4s in a row!) and it thinks it solves the problem. I haven’t investigated it completely.<br />
Am more interested in understanding the monads than solving Sudokus.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/kapilash.wordpress.com/8/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/kapilash.wordpress.com/8/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kapilash.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kapilash.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kapilash.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kapilash.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kapilash.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kapilash.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kapilash.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kapilash.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kapilash.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kapilash.wordpress.com/8/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kapilash.wordpress.com&blog=1696932&post=8&subd=kapilash&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://kapilash.wordpress.com/2008/05/11/monadic-combinators-for-sudoku/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e5f6c043a7fc3e5a20d6df63b1fa70c4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kapilash</media:title>
		</media:content>
	</item>
		<item>
		<title>Simple Sudoku Solver</title>
		<link>http://kapilash.wordpress.com/2008/05/09/simple-sudoku-solver/</link>
		<comments>http://kapilash.wordpress.com/2008/05/09/simple-sudoku-solver/#comments</comments>
		<pubDate>Fri, 09 May 2008 17:21:53 +0000</pubDate>
		<dc:creator>kapilash</dc:creator>
				<category><![CDATA[haskell]]></category>

		<guid isPermaLink="false">http://kapilash.wordpress.com/?p=7</guid>
		<description><![CDATA[
In this post and the next, I will document my attempts in writing a sudoku solver in haskell. In the current post, I will present a native implementation..

1 Problem statement

Sudoku needs no introduction. A sample is given below.





C0
C1
C2
C3
C4
C5
C6
C7
C8


r0


5

4

7
3
9


r1

7
6


9
5




r2




7

6
8



r3

8



7
3




r4
6

7

1

2

8


r5


3
2



1



r6

6
9

3






r7


8
1


4
7



r8
2
1
4

6

8







1.1 constraints

The idea is to fill the empty spaces with digits 1 to 9 so that the grid [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kapilash.wordpress.com&blog=1696932&post=7&subd=kapilash&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><!--CUT DEF section 1 --></p>
<p>In this post and the next, I will document my attempts in writing a sudoku solver in haskell. In the current post, I will present a native implementation..</p>
<p><!--TOC section Problem statement--></p>
<h2 class="section"><!--SEC ANCHOR --><a name="htoc1">1</a> Problem statement</h2>
<p><!--SEC END --></p>
<p>Sudoku needs no introduction. A sample is given below.</p>
<div class="center">
<table border="1" cellspacing="0" cellpadding="1">
<tbody>
<tr>
<td align="left"></td>
<td align="right">C0</td>
<td align="right">C1</td>
<td align="right">C2</td>
<td align="right">C3</td>
<td align="right">C4</td>
<td align="right">C5</td>
<td align="right">C6</td>
<td align="right">C7</td>
<td align="right">C8</td>
</tr>
<tr>
<td align="left">r0</td>
<td align="right"></td>
<td align="right"></td>
<td align="right">5</td>
<td align="right"></td>
<td align="right">4</td>
<td align="right"></td>
<td align="right">7</td>
<td align="right">3</td>
<td align="right">9</td>
</tr>
<tr>
<td align="left">r1</td>
<td align="right"></td>
<td align="right">7</td>
<td align="right">6</td>
<td align="right"></td>
<td align="right"></td>
<td align="right">9</td>
<td align="right">5</td>
<td align="right"></td>
<td align="right"></td>
</tr>
<tr>
<td align="left">r2</td>
<td align="right"></td>
<td align="right"></td>
<td align="right"></td>
<td align="right"></td>
<td align="right">7</td>
<td align="right"></td>
<td align="right">6</td>
<td align="right">8</td>
<td align="right"></td>
</tr>
<tr>
<td align="left">r3</td>
<td align="right"></td>
<td align="right">8</td>
<td align="right"></td>
<td align="right"></td>
<td align="right"></td>
<td align="right">7</td>
<td align="right">3</td>
<td align="right"></td>
<td align="right"></td>
</tr>
<tr>
<td align="left">r4</td>
<td align="right">6</td>
<td align="right"></td>
<td align="right">7</td>
<td align="right"></td>
<td align="right">1</td>
<td align="right"></td>
<td align="right">2</td>
<td align="right"></td>
<td align="right">8</td>
</tr>
<tr>
<td align="left">r5</td>
<td align="right"></td>
<td align="right"></td>
<td align="right">3</td>
<td align="right">2</td>
<td align="right"></td>
<td align="right"></td>
<td align="right"></td>
<td align="right">1</td>
<td align="right"></td>
</tr>
<tr>
<td align="left">r6</td>
<td align="right"></td>
<td align="right">6</td>
<td align="right">9</td>
<td align="right"></td>
<td align="right">3</td>
<td align="right"></td>
<td align="right"></td>
<td align="right"></td>
<td align="right"></td>
</tr>
<tr>
<td align="left">r7</td>
<td align="right"></td>
<td align="right"></td>
<td align="right">8</td>
<td align="right">1</td>
<td align="right"></td>
<td align="right"></td>
<td align="right">4</td>
<td align="right">7</td>
<td align="right"></td>
</tr>
<tr>
<td align="left">r8</td>
<td align="right">2</td>
<td align="right">1</td>
<td align="right">4</td>
<td align="right"></td>
<td align="right">6</td>
<td align="right"></td>
<td align="right">8</td>
<td align="right"></td>
<td align="right"></td>
</tr>
</tbody>
</table>
</div>
<p><!--TOC subsection constraints--></p>
<h3 class="subsection"><!--SEC ANCHOR --><a name="htoc2">1.1</a> constraints</h3>
<p><!--SEC END --></p>
<p>The idea is to fill the empty spaces with digits 1 to 9 so that the grid satisfies the following conditions:</p>
<ol class="enumerate" type="1">
<li class="li-enumerate"> each row contains exactly one occurence of each of the digits from 1 to 9.</li>
<li class="li-enumerate">each column contains exactly one occurence of each of the digits from 1 to9.</li>
<li class="li-enumerate">each block contains exactly one occurence of each of the digits from 1 to 9, where block is a 3X3 grid. An example block<br />
is the one at the top left corner containing the following cells &#8211; (0,0),(0,1),(0,2),(1,0),(1,1),<br />
(2,2),(2,0),(2,1),(2,2).<br />
There are nine such blocks. The ninth block comprising (6,6),(6,7),(6,8),<br />
(7,6),(7,7),(7,8),(8,6),(8,7) and (8,8).</li>
</ol>
<p><!--TOC section Solution approach--></p>
<h2 class="section"><!--SEC ANCHOR --><a name="htoc3">2</a> Solution approach</h2>
<p><!--SEC END --><!--TOC subsection Cell--></p>
<h3 class="subsection"><!--SEC ANCHOR --><a name="htoc4">2.1</a> Cell</h3>
<p><!--SEC END --></p>
<p>The basic unit here is a cell. So let us consider a data-type Cell defined as below:</p>
<pre>data Cell =  FilledCell Int
           | EmptyCell [Int]
</pre>
<p>where, the empty cell represents a list of possible values that cell can hold. Initially, the list of possible values is the list<br />
[1,2,3,4,5,6,7,8,9] and when it becomes a single-celled list, the cell moves into a filledCell.</p>
<p>A two-dimensional array (or a list of lists) is an almost obvious choice as the data structure for representing the whole grid at various stages of the solution.</p>
<p>So, the type for Sudoku can be:</p>
<pre> type Sudoku = Array (Int,Int) Cell
</pre>
<p>We will be given with an initial Sudoku containing a lots of EmptyCells and a few FilledCells.</p>
<p><!--TOC subsection Algorithm--></p>
<h3 class="subsection"><!--SEC ANCHOR --><a name="htoc5">2.2</a> Algorithm</h3>
<p><!--SEC END --></p>
<p>A naive algorithm for solving the Sudoku can be described as:</p>
<ol class="enumerate" type="1">
<li class="li-enumerate"> check the type of a cell.</li>
<li class="li-enumerate">if it is a filled cell, move to the next one</li>
<li class="li-enumerate">if the cell is an empty cell with a unary list, convert it into a FilledCell and move to the next one.</li>
<li class="li-enumerate">if the cell has more than one possible values,get the values from all the <em>related</em> cells.<br />
Narrow the scope of the cell by removing all these values from the list of the cell. And move on to the next cell.</li>
<li class="li-enumerate">repeat the step for all the cells.</li>
</ol>
<p><!--TOC section Implementation--></p>
<h2 class="section"><!--SEC ANCHOR --><a name="htoc6">3</a> Implementation</h2>
<p><!--SEC END --></p>
<p>Starting off with a few lines about module and data definitions,</p>
<p><!--TOC subsection Data types and modules--></p>
<h3 class="subsection"><!--SEC ANCHOR --><a name="htoc7">3.1</a> Data types and modules</h3>
<p><!--SEC END --></p>
<pre><span style="font-size:x-small;">
module Sudoku where</span>

<span style="font-size:x-small;">import Data.Array</span>

<span style="font-size:x-small;">data Cell =  FilledCell Int
           | EmptyCell [Int]
           deriving Show</span>

<span style="font-size:x-small;">type Sudoku = Array (Int,Int) Cell
</span></pre>
<p><!--TOC subsection Input--></p>
<h3 class="subsection"><!--SEC ANCHOR --><a name="htoc8">3.2</a> Input</h3>
<p><!--SEC END --></p>
<p>Let’s say that we get the input in the form of a list of lists. An example is given below:</p>
<pre><span style="font-size:x-small;">puzzle ::[[Int]]
puzzle =[[0, 0, 5, 0, 4, 0, 7, 3, 9],
         [0, 7, 6, 0, 0, 9, 5, 0, 0],
         [0, 0, 0, 0, 7, 0, 6, 8, 0],
         [0, 8, 0, 0, 0, 7, 3, 0, 0],
         [6, 0, 7, 0, 1, 0, 2, 0, 8],
         [0, 0, 3, 2, 0, 0, 0, 1, 0],
         [0, 6, 9, 0, 3, 0, 0, 0, 0],
         [0, 0, 8, 1, 0, 0, 4, 7, 0],
         [2, 1, 4, 0, 6, 0, 8, 0, 0]] </span>

<span style="font-size:x-small;">evil ::[[Int]]
evil = [[0, 0, 0, 0, 0, 0, 4, 0, 0],
        [1, 0, 8, 3, 0, 0, 2, 0, 5],
        [0, 6, 0, 0, 0, 9, 0, 0, 3],
        [0, 0, 0, 7, 0, 5, 0, 8, 0],
        [0, 0, 9, 0, 0, 0, 7, 0, 0],
        [0, 7, 0, 8, 0, 1, 0, 0, 0],
        [9, 0, 0, 4, 0, 0, 0, 2, 0],
        [5, 0, 1, 0, 0, 3, 8, 0, 7],
        [0, 0, 4, 0, 0, 0, 0, 0, 0]]</span>

<span style="font-size:x-small;">hard :: [[Int]]
hard = [[0,0,7,0,2,0,0,1,0],
        [0,0,0,0,0,0,4,5,0],
        [4,0,0,9,7,0,0,0,0],
        [0,0,0,3,0,0,0,0,4],
        [6,3,4,0,0,0,2,9,5],
        [9,0,0,0,0,4,0,0,0],
        [0,0,0,0,8,7,0,0,2],
        [0,1,2,0,0,0,0,0,0],
        [0,5,0,0,4,0,9,0,0]]</span>

<span style="font-size:x-small;">medium :: [[Int]]
medium = [[0, 0, 0, 2, 0, 0, 7, 0, 0],
          [2, 5, 7, 0, 0, 0, 4, 6, 0],
          [0, 6, 0, 7, 0, 9, 0, 0, 0],
          [0, 2, 0, 3, 0, 7, 6, 0, 0],
          [5, 0, 8, 0, 0, 0, 3, 0, 4],
          [0, 0, 6, 4, 0, 1, 0, 5, 0],
          [0, 0, 0, 9, 0, 8, 0, 3, 0],
          [0, 3, 9, 0, 0, 0, 8, 4, 7],
          [0, 0, 2, 0, 0, 4, 0, 0, 0]]</span></pre>
<p>I need a function to convert this into a <em>Sudoku</em>.</p>
<p>But before that I need to construct a basic Grid containing all empty cells</p>
<pre><span style="font-size:x-small;">getInitSudoku :: Sudoku
getInitSudoku = array ((0,0),(8,8)) ([((i,j),EmptyCell [1..9]) | i &lt;- [0..8], j&lt;-[0..8] ])
</span></pre>
<p>Now a function that takes a single dimensional list of Integers (easily obtained from something like puzzle above using a <em>foldr</em> and a  ++ ).</p>
<pre><span style="font-size:x-small;">fromList :: [Int]-&gt;(Int,Int)-&gt;Sudoku-&gt;Sudoku
fromList [] _ sudoku = sudoku
fromList (x:xs) (row,col) sudoku = let
                                    nextCol = mod (col + 1) 9
                                    nextRow = if (nextCol == 0 ) then row +1 else row
                                  in if x == 0  then fromList xs (nextRow,nextCol) sudoku
                                      else fromList xs (nextRow,nextCol) (sudoku // [((row,col),(FilledCell x))])</span></pre>
<p>Here,I will define a function that takes two lists A and B as input and returns a list containing only those elements of A that are not there in B.<br />
For example, if the input is [1,8,7,6,3] and [9,8,3] then the output should be [1,7,6] (8 and 3 being members in second list too.)<br />
Since the lists that this function will be dealing with will have lengths of about 9 or 10, I will put a blind eye on<br />
the fact that <em>elem</em> is of O(n) and is slow for large values of n. I am defining the function here as an operator.<br />
So, here goes the function:</p>
<pre><span style="font-size:x-small;">(#) :: Eq a =&gt;[a] -&gt;[a]-&gt;[a]
(#) [] b = []
(#) a [] = a
(#) (ah:atail) b = if ( ah `elem` b) then ((#) atail b)
       else (ah: ((#) atail b))
</span></pre>
<p><!--TOC subsection Identifying related cells--></p>
<h3 class="subsection"><!--SEC ANCHOR --><a name="htoc9">3.3</a> Identifying related cells</h3>
<p><!--SEC END --></p>
<p>Now I’ll write a function to identify the related cells. That is given a pair of coordinates, I will get a list of (Int,Int)s containing<br />
the indices of all the relevant cells.<br />
For example, if my input is (0,0) the expected output is<br />
[(0,1),(0,2),(0,3)…(0..8),(1,0),(2,0),(3,0) …(8,0),(0,0),(0,1),(0,2),(1,0),(1,1),<br />
(2,2),(2,0),(2,1),(2,2)]</p>
<p>Let me divide into three simpler steps :</p>
<ol class="enumerate" type="1">
<li class="li-enumerate"> A function that takes the row-column pair and gives the list of all indices in the current row.</li>
<li class="li-enumerate">A function that takes the row-column pair and gives the list of all indices in the current row</li>
<li class="li-enumerate">A function that takes the row-column pair and gives the list of all indices in the current block</li>
</ol>
<p>Functions for the first two are <em>beautiful</em> in a lazy functional language like haskell.</p>
<pre><span style="font-size:x-small;">interestedRow :: (Int,Int) -&gt; [(Int,Int)]
interestedRow (row,col) = zip [row,row..row] [0..8]</span>

<span style="font-size:x-small;">interestedColumn :: (Int,Int) -&gt; [(Int,Int)]
interestedColumn (row,col) = zip [0..8] [col,col..col]
</span></pre>
<p>The third function is a bit agricultural compared to the above two. The idea here is to identify the “block-indices”.<br />
In other words, there are nine blocks in a 3X3 matrix. Their indices are (0,0),(0,1),(0,2) …(2,1),(2,2).<br />
If we know the block indices, the list is straight forward &#8211;  (3*<em>br</em>,3*<em>bc</em>), (3*<em>br</em> + 1,3*<em>bc</em>) … (3*<em>br</em> +2,3*<em>bc</em>+2)</p>
<pre><span style="font-size:x-small;">interestedBlock :: (Int,Int) -&gt; [(Int,Int)]
interestedBlock (row,col) = let
                               br = 3 * (  row `div` 3 )
                               bc = 3 *( col `div` 3 )
                            in [(br,bc),(br,bc+1),(br,bc+2),
                                (br+1,bc),(br+1,bc+1),(br+1,bc+2),
                                (br+2,bc),(br+2,bc+1),(br+2,bc+2)]
</span></pre>
<p>With the above three functions in place, the function which gives all the relevant indices is straight forward.<br />
We concatenate the lists from above functions and remove the current index.</p>
<pre><span style="font-size:x-small;">relevantIndices = \x -&gt; ( ( (interestedRow x) ++ (interestedColumn x) ++ (interestedBlock x) ) # [x] )
</span></pre>
<p>Now it is time to define a function that takes the Sudoku and a list of indices and returns a list of non-zero values at the indices</p>
<pre><span style="font-size:x-small;">relatedVals :: Sudoku-&gt;[(Int,Int)]-&gt;[Int]
relatedVals sudoku []      = []
relatedVals sudoku (x:xs)  = case (sudoku ! x ) of
                                  (FilledCell v) -&gt; ( v : (relatedVals sudoku xs) )
                                  (EmptyCell l)  -&gt; (relatedVals sudoku xs)</span></pre>
<p><!--TOC section Reduction--></p>
<h2 class="section"><!--SEC ANCHOR --><a name="htoc10">4</a> Reduction</h2>
<p><!--SEC END --></p>
<p>In this section, I’ll define the functions that try to reduce the scope of the empty cells.</p>
<p><!--TOC subsection At the cellular level--></p>
<h3 class="subsection"><!--SEC ANCHOR --><a name="htoc11">4.1</a> At the cellular level</h3>
<p><!--SEC END --></p>
<p>The first reduction function, <em>simpleReduction</em> operates at the level of a cell.<br />
It takes the <em>Sudoku</em> and an index and returns a new <em>Sudoku</em> such that the cell at the index is updated either with a FilledCell or an emptyCell with reduced scope.</p>
<pre><span style="font-size:x-small;">
simpleReduction :: Sudoku -&gt;(Int,Int) -&gt; Sudoku
simpleReduction sudoku (row,col) = case (sudoku ! (row,col)) of
                                      FilledCell v       -&gt; sudoku
                                      EmptyCell (solo:[])-&gt; sudoku // [( (row,col),FilledCell solo)]
                                      EmptyCell list     -&gt; sudoku // (getNewList sudoku (row,col) list)</span>

<span style="font-size:x-small;">getNewList :: Sudoku -&gt; (Int,Int)-&gt; [Int] -&gt; [((Int,Int),Cell)]
getNewList sudoku (row,col) lst =  let
                                     neededIndices  = relevantIndices (row,col)
                                     otherValues    = relatedVals sudoku neededIndices
                                     newlst         = lst # otherValues
                                   in  case newlst of
                                          (h:[]) -&gt; [((row,col),(FilledCell h))]
                                          (x:xs) -&gt; [((row,col),(EmptyCell (x:xs)))]</span></pre>
<p><!--TOC subsection A recursive function on the whole--></p>
<h3 class="subsection"><!--SEC ANCHOR --><a name="htoc12">4.2</a> A recursive function on the whole</h3>
<p><!--SEC END --></p>
<p>Now I need a function that applies the function, <em>simpleReduction</em> on all the cells.</p>
<pre><span style="font-size:x-small;">reduceSudoku1 sudoku (9,0)    = sudoku
reduceSudoku1 sudoku (row,col)= let
                                       nextCol = mod (col + 1) 9
                                       nextRow = if (nextCol == 0 ) then row + 1 else row
                                in
                                      reduceSudoku1 (simpleReduction sudoku (row,col)) (nextRow,nextCol)
</span></pre>
<p>Now a function to check if there are any empty cells still left in the grid.</p>
<pre><span style="font-size:x-small;">hasEmptyCells sudoku (9,0)     = False
hasEmptyCells sudoku (row,col) = let
                                       nextCol = mod (col + 1) 9
                                       nextRow = if (nextCol == 0 ) then row + 1 else row
                                 in
                                      case (sudoku ! (row,col) ) of
                                        FilledCell v -&gt; hasEmptyCells sudoku (nextRow,nextCol)
                                        EmptyCell l  -&gt; True</span>

<span style="font-size:x-small;">numEmptyCells :: Sudoku -&gt;(Int,Int)-&gt;Int-&gt;Int
numEmptyCells sudoku (9,0) count    = count
numEmptyCells sudoku (row,col)count = let
                                         nextCol = mod (col + 1) 9
                                         nextRow = if (nextCol == 0 ) then row + 1 else row
                                      in
                                       case (sudoku ! (row,col) ) of
                                          FilledCell v -&gt; numEmptyCells sudoku (nextRow,nextCol) count
                                          EmptyCell l  -&gt; numEmptyCells sudoku (nextRow,nextCol) (count + 1)</span></pre>
<p>That leaves me with a function that applies the reduceSudoku1 function, a few times, say 10 times.<br />
It breaks, if it encounters a completely filled sudoku before.</p>
<pre><span style="font-size:x-small;">loop10Max sudoku count
         | (count &lt; 10) &amp;&amp;  (hasEmptyCells sudoku (0,0))  = loop10Max (reduceSudoku1 sudoku (0,0)) (count + 1)
         | otherwise                                      = (sudoku,count)</span></pre>
<p>A better function would be something that would apply reduceSudoku1 till it is useful.<br />
Such a function will continue applying the naive algorithm as long as there is some improvement of applying the algo.The moment it finds no improvement, it breaks.</p>
<pre><span style="font-size:x-small;">loopTillDone :: Sudoku -&gt; Sudoku
loopTillDone sudoku = loopTillDoneHelper sudoku (numEmptyCells sudoku (0,0) 0)</span>

<span style="font-size:x-small;">loopTillDoneHelper :: Sudoku-&gt;Int -&gt; Sudoku
loopTillDoneHelper sudoku count = let
                                     nextRound = reduceSudoku1 sudoku (0,0)
                                     countNext = numEmptyCells nextRound (0,0) 0
                                  in
                                    if (countNext &lt; count) then loopTillDoneHelper nextRound countNext
                                    else nextRound</span></pre>
<p><!--TOC section Trying it out--></p>
<h2 class="section"><!--SEC ANCHOR --><a name="htoc13">5</a> Trying it out</h2>
<p><!--SEC END --></p>
<p>Now I can try the stuff out on some sample Sudokus. I will load the current file (Sudoku.lhs) in ghci and run the functions using:</p>
<pre>let list = foldr (++) []  puzzle
let sudoku1 = fromList list (0,0) getInitSudoku
let (s,c) = loop10Max sudoku1 0</pre>
<p>Just typing ‘s’ on the command prompt will print out the solved Sudoku. However, all is not well. Trying the problem on harder puzzles<br />
(using ‘evil’ or ‘hard’ in place of ‘puzzle’ in the above), I can see that the naive algorithm I used so far is pretty inadequate for<br />
complicated puzzles. We have been filling only those cells that can be filled because of data in related cells. This does not know how to make a guess and see if it is correct and backtrack if the guess happens to be a wrong one.<br />
In the next chapter, I’ll see how I can rectify this.</p>
<p>PS: This page has been written in literate haskell and has been converted into html using <a title="hevea" href="http://pauillac.inria.fr/hevea/" target="_blank">hevea</a></p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/kapilash.wordpress.com/7/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/kapilash.wordpress.com/7/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kapilash.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kapilash.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kapilash.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kapilash.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kapilash.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kapilash.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kapilash.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kapilash.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kapilash.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kapilash.wordpress.com/7/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kapilash.wordpress.com&blog=1696932&post=7&subd=kapilash&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://kapilash.wordpress.com/2008/05/09/simple-sudoku-solver/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e5f6c043a7fc3e5a20d6df63b1fa70c4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kapilash</media:title>
		</media:content>
	</item>
		<item>
		<title>First steps into haskell Type Classes</title>
		<link>http://kapilash.wordpress.com/2008/05/04/first-steps-into-haskell-type-classes/</link>
		<comments>http://kapilash.wordpress.com/2008/05/04/first-steps-into-haskell-type-classes/#comments</comments>
		<pubDate>Sun, 04 May 2008 17:54:48 +0000</pubDate>
		<dc:creator>kapilash</dc:creator>
				<category><![CDATA[haskell]]></category>

		<guid isPermaLink="false">http://kapilash.wordpress.com/?p=6</guid>
		<description><![CDATA[A Generic Z Algorithm
As mentioned earlier, the biggest problem with the ZAlgo funtion defined in the previous blog is
that it works for only a fixed types of inputs. It takes a String and produces a ByteString (apart from ZAlgoDS). And that is a gross injustice to the algorithm which works for just about any sequences.
The [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kapilash.wordpress.com&blog=1696932&post=6&subd=kapilash&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>A Generic Z Algorithm</p>
<p>As mentioned earlier, the biggest problem with the ZAlgo funtion defined in the <a title="previous blog" href="http://kapilash.wordpress.com/2008/04/29/z-algorithm-in-haskell/" target="_self">previous blog</a> is<br />
that it works for only a fixed types of inputs. It takes a String and produces a ByteString (apart from ZAlgoDS). And that is a gross injustice to the algorithm which works for just about any sequences.<br />
The algorithm works for sequences of all types &#8211; sequences of integers, characters, even sequences of Strings or any ADT for that matter.<br />
In this chapter, we will make the ZAlgo function handle all types of data.</p>
<p>In this blog, I will make the ZAlgo function, generic enough to handle other types of sequences also.<br />
That is, the new module which I will define now can be used for processing any kinds of sequences.</p>
<p>I&#8217;ll continue to use the <strong>Data.Array</strong> for holding the Z Array(and not consider any generic-ness here), for the sake of simplicity  although there are other options available in Standard libraries of the haskell to hold similar structure with perhaps better performance.</p>
<pre><code>
<span>module GenZ where
</span></code></pre>
<p><code><span><br />
import Data.Array</span></code></p>
<p>import Data.ByteString.Char8 as B</p>
<p><span><br />
</span><br />
The second import(Data.ByteString.Char8 ) is used only for the instance declaration (in the usage section). It is not used in the main algo</p>
<p><span><br />
<code><br />
type Zs = Array Int Int<br />
</code><br />
</span><br />
<span><br />
<code> </code></span></p>
<pre><span>data ZAlgoDS = ZAlgoDS{  zeds ::Zs, rSoFar ::Int, lSoFar::Int} deriving Show
</span></pre>
<p>Now we need a <em>class</em> for which the functions can be defined. A class in haskell is a collection of related <em>types</em>.</p>
<h3><a name="tth_sEc1"><br />
1</a> Class Declaration</h3>
<pre><code>
<span>class MyString m  where
           zEqAtIndex  :: (m,Int)-&gt;(m,Int)-&gt;Bool
           zLength     :: m -&gt; Int

</span></code></pre>
<p>This is the type we will use while defining the functions to create a generic algorithm.</p>
<h3><a name="tth_sEc2"><br />
2</a> Comparison of the sequences</h3>
<pre><code>
<span>compareStr :: (MyString m)=&gt; (m,Int)-&gt;(m,Int)-&gt;Int-&gt;Int
compareStr (s1,pos1) (s2,pos2) soFar
            |  (pos1 &lt; zLength  s1) || (pos2 &lt; zLength s2) =  let
                                                                      compRes = zEqAtIndex (s1,pos1) (s2,pos2)
                                                                   in
                                                                      if compRes    then
                                                   compareStr (s1,(pos1 + 1)) (s2, (pos2 + 1)) (soFar + 1)
                                                                      else soFar

            |  otherwise                                        = soFar
</span></code></pre>
<p>As can be seen above, we barely made two changes :</p>
<ol type="1">
<li> We used zEqAtIndex to compare the items at respective positions</li>
<li> we are using zLength instead of B.length</li>
</ol>
<h3><a name="tth_sEc3"><br />
3</a> getZAt</h3>
<p>Moving on, getZAt method can be modified in similar fashion<br />
<span><br />
<code> </code></span></p>
<pre><span>getZAt :: (MyString m)=&gt; m -&gt; Int -&gt;Int
getZAt str 0 =  zLength str
getZAt str pos
         |  (pos &gt;0) &amp;&amp; (pos &lt; zLength str) = compareStr (str,0) (str,pos) 0
         |  otherwise = error Ïndex out of range"

</span></pre>
<h3><a name="tth_sEc4"><br />
4</a> Initializing the z array</h3>
<p>There need not be any change in this function.<br />
<span><br />
<code> </code></span></p>
<pre><span>getInitZArray :: Int -&gt; Zs
getInitZArray lngth = array (0,lngth) ( (0,(lngth+1)) : [(i,0)  -  i &lt;- [1..lngth]])
</span></pre>
<h3><a name="tth_sEc5"><br />
5</a> zAlgo and its helper functions</h3>
<p>In zAlgo and its helper functions, the only change we need to do is using the zLength instead of the library function</p>
<pre><code>
<span>zAlgo str (ZAlgoDSzeds = zds,rSoFar=r,lSoFar = l)  pos
	 -  (pos &gt;= zLength str) = ZAlgoDSzeds = zds, rSoFar =r , lSoFar =l
	 -  (pos &gt;= r ) = zAlgo str (helper1 str pos zds r l) (pos +1)
	 -  otherwise = zAlgo str (helper2 str pos zds r l) (pos + 1)
</span></code></pre>
<p>Both the first of the helper functions</p>
<pre><code>
<span>helper1 str pos zs r l = let
			   zpos = getZAt str pos
                           r' = pos + zpos - 1
                         in
                           if (zpos == 0 ) then ZAlgoDSzeds = zs,rSoFar =r,lSoFar =l
	                   else ZAlgoDS zeds = (zs // [(pos,zpos)]), rSoFar = r',lSoFar = pos
</span></code></pre>
<pre><code>
<span>helper2 str pos zs r l = let
			   k' = pos - l
                           zk' = zs ! k'
                           beta = r - pos +1
                         in
                           if ( zk' &lt;= beta ) then ZAlgoDSzeds = (zs//[(pos,zk')]),rSoFar =r,lSoFar =l
	                   else
                              let
				q  = compareStr (str,beta) (str,r) 0
                                r' = r + q
                                l' = pos
	                        zpos = r' - l' + 1
                               in ZAlgoDSzeds = (zs //[(pos,zpos)]),rSoFar =r',lSoFar=l'
</span></code></pre>
<p>remain largely unaltered.</p>
<p>That completes generalizing the algorithm, so that it can process any sequence of characters.Now comes the complicated part.</p>
<h3><a name="tth_sEc6"><br />
6</a> Usage</h3>
<p>I&#8217;llo use the same functions above for two different types of sequences.</p>
<p>I&#8217;ll first define a couple of dummy functions to compare at indices &#8211; one for Binary Strings and one for Lists-Of-Strings</p>
<pre><code>
<span>compAtIndices :: (B.ByteString,Int)-&gt;(B.ByteString,Int) -&gt; Bool
compAtIndices (s1,pos1) (s2,pos2) = (B.index s1 pos1) == (B.index s2 pos2)
</span></code></pre>
<p><span><code>data LoS = LoS [String] deriving (Show)</code></span></p>
<pre><code>
<span>compStrAtIndices :: (LoS,Int)-&gt;(LoS,Int)-&gt;Bool
compStrAtIndices (LoS sList1,pos1) (LoS sList2,pos2) = ((sList1 !! pos1) == (sList2 !! pos2))
</span></code></pre>
<pre><code>
<span>getLength :: LoS -&gt; Int
getLength (LoS slist) = Prelude.length slist
</span></code></pre>
<p>Now a couple of instances</p>
<pre><code>
<span>instance MyString  B.ByteString  where
      zEqAtIndex    = compAtIndices
      zLength       = B.length
</span></code></pre>
<p><span> </span><span><br />
<code> </code></span></p>
<pre><span>instance MyString  LoS  where
      zEqAtIndex    = compStrAtIndices
      zLength       = getLength
</span></pre>
<p><span> </span></p>
<h3><a name="tth_sEc7"><br />
7</a> Wrapper Function</h3>
<p>Now, the wrapper functions. One for ByteString and one for LoS</p>
<pre><code>
<span>zMain :: String -&gt; (B.ByteString,ZAlgoDS)
zMain str = let
              byteString  = B.pack str
              zinit       = getInitZArray ((B.length byteString) - 1)
              zDataStruct = ZAlgoDS zeds = zinit,rSoFar = 0,lSoFar = 0
            in
              (byteString,(zAlgo byteString zDataStruct 1))
</span></code></pre>
<pre><code>
<span>zMain' :: [String] -&gt; (LoS,ZAlgoDS)
zMain' strList = let
                   zinit       = getInitZArray ((Prelude.length strList) - 1)
                   zDataStruct = ZAlgoDS zeds = zinit,rSoFar = 0,lSoFar = 0
                 in
                     (LoS strList,(zAlgo (LoS strList) zDataStruct 1))
</span></code></pre>
<p>Now, we are done.<br />
we can use zMain to process strings and zMain&#8217; to process lists of strings.</p>
<p>In general, we can thus use the same algorithm to process a linear list/sequence of any data types. The OOPs equivalent of this is , perhaps the strategy design pattern.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/kapilash.wordpress.com/6/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/kapilash.wordpress.com/6/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kapilash.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kapilash.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kapilash.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kapilash.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kapilash.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kapilash.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kapilash.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kapilash.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kapilash.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kapilash.wordpress.com/6/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kapilash.wordpress.com&blog=1696932&post=6&subd=kapilash&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://kapilash.wordpress.com/2008/05/04/first-steps-into-haskell-type-classes/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e5f6c043a7fc3e5a20d6df63b1fa70c4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kapilash</media:title>
		</media:content>
	</item>
		<item>
		<title>Z Algorithm in Haskell</title>
		<link>http://kapilash.wordpress.com/2008/04/29/z-algorithm-in-haskell/</link>
		<comments>http://kapilash.wordpress.com/2008/04/29/z-algorithm-in-haskell/#comments</comments>
		<pubDate>Tue, 29 Apr 2008 21:03:34 +0000</pubDate>
		<dc:creator>kapilash</dc:creator>
				<category><![CDATA[haskell]]></category>

		<guid isPermaLink="false">http://kapilash.wordpress.com/?p=4</guid>
		<description><![CDATA[Z Algorithm in Haskell using ByteString<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kapilash.wordpress.com&blog=1696932&post=4&subd=kapilash&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>I tried to implement, in haskell, the Z Algorithm given in Dan Gusfield&#8217;s <a title="Algorithms on Strings, Trees and Sequences" href="http://www.amazon.com/Algorithms-Strings-Trees-Sequences-Computational/dp/0521585198" target="_blank">Algorithms on Strings,trees and Sequences.</a></p>
<p>It  is not the prettiest, fastest and definitely not the most elegant implementation of this algorithm in haskell,but it sure taught me a trick or two. In this post, I&#8217;ll  limit myself with a naive-implementation of the algorithm. And in later blogs, I will attempt at improving the same. Here&#8217;s the code &#8211; warts and all.</p>
<pre><code>
module ZAlgo where

import Data.ByteString.Char8 as B
import Data.Array

type Zs = Array Int Int

data ZAlgoDS = ZAlgoDS { zeds ::Zs, rSoFar ::Int, lSoFar::Int} deriving Show

compareStr :: (B.ByteString,Int)-&gt;(B.ByteString,Int)-&gt;Int -&gt;Int
compareStr (s1,pos1) (s2,pos2) soFar
           | (pos1 &lt; B.length  s1) &amp;&amp;  (pos2 &lt; B.length s2) =  let
                                                                  c1 = B.index s1 pos1
                                                                  c2 = B.index s2 pos2
                                                                in
                                                                  if(c1 == c2)    then
                                      compareStr (s1,(pos1 + 1)) (s2, (pos2 + 1)) (soFar + 1)
                                                                  else soFar

           | otherwise                                        = soFar

getZAt ::B.ByteString -&gt; Int-&gt; Int
getZAt str 0 =  B.length str
getZAt str pos
        | (pos &gt;0) &amp;&amp; (pos &lt; B.length str) = compareStr (str,0) (str,pos) 0
        | otherwise = error "Index out of range"

getInitZArray :: Int -&gt; Zs
getInitZArray lngth = array (0,lngth) ( (0,(lngth+1)) : [(i,0) | i &lt;- [1..lngth]])

zAlgo :: B.ByteString -&gt; ZAlgoDS -&gt; Int -&gt; ZAlgoDS
zAlgo str (ZAlgoDS{zeds = zds,rSoFar=r,lSoFar = l})  pos
	| (pos &gt;= B.length str) = ZAlgoDS{zeds = zds, rSoFar =r , lSoFar =l}
	| (pos &gt;= r ) = zAlgo str (helper1 str pos zds r l) (pos +1)
	| otherwise = zAlgo str (helper2 str pos zds r l) (pos + 1)

helper1 :: B.ByteString -&gt; Int -&gt; Zs -&gt; Int -&gt;Int -&gt; ZAlgoDS
helper1 str pos zs r l = let
			   zpos = getZAt str pos
                           r' = pos + zpos - 1
                         in
                           if (zpos == 0 ) then ZAlgoDS{zeds = zs,rSoFar =r,lSoFar =l}
	                   else ZAlgoDS{ zeds = (zs // [(pos,zpos)]), rSoFar = r',lSoFar = pos}

helper2 :: B.ByteString -&gt; Int -&gt; Zs -&gt; Int -&gt;Int -&gt; ZAlgoDS
helper2 str pos zs r l = let
			   k' = pos - l
                           zk' = zs ! k'
                           beta = r - pos +1
                         in
                           if ( zk' &lt;= beta ) then ZAlgoDS{zeds = (zs//[(pos,zk')]),rSoFar =r,lSoFar =l}
	                   else
                              let
				q  = compareStr (str,beta) (str,r) 0
                                r' = r + q
                                l' = pos
	                        zpos = r' - l' + 1
                               in ZAlgoDS{zeds = (zs //[(pos,zpos)]),rSoFar =r',lSoFar=l'}

zMain :: String -&gt; (B.ByteString,ZAlgoDS)
zMain str = let
              byteString  = B.pack str
              zinit       = getInitZArray ((B.length byteString) - 1)
              zDataStruct = ZAlgoDS {zeds = zinit,rSoFar = 0,lSoFar = 0}
            in
              (byteString,(zAlgo byteString zDataStruct 1))

</code></pre>
<p>A small Main.hs &#8211; that takes the string to be preprocessed and prints it out:</p>
<pre><code>
module Main where

import ZAlgo
import System

main = do
      args &lt;- getArgs
      print $ show (zMain (head args))
</code></pre>
<p>To compile the code : <strong>ghc &#8211;make Main.hs </strong></p>
<p>and to run <strong>./Main &lt;string-to-be-preprocessed&gt;</strong></p>
<p>I&#8217;ve also played around with a few interesting options are to use the <a title="-hprof" href="http://haskell.org/ghc/docs/latest/html/users_guide/profiling.html" target="_blank">&#8220;-prof&#8221;</a> option of the ghc to see some profiling data and using the <a title="-fhpc" href="http://haskell.org/ghc/docs/latest/html/users_guide/hpc.html" target="_blank">-fhpc</a> option to get the code coverage for a given input. More about them later.<br />
Not counting the amateurish function names and  the very-inelegant-for-haskell-standards code (and even potential bugs!), there&#8217;s a major drawback with the implementation. Wheras, the algorithm is pretty generic &#8211; it can handle any types of sequences, the above code can handle only a sequence of characters (that too a single byte characters, I think). In the next post, I will rectify that.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/kapilash.wordpress.com/4/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/kapilash.wordpress.com/4/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kapilash.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kapilash.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kapilash.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kapilash.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kapilash.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kapilash.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kapilash.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kapilash.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kapilash.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kapilash.wordpress.com/4/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kapilash.wordpress.com&blog=1696932&post=4&subd=kapilash&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://kapilash.wordpress.com/2008/04/29/z-algorithm-in-haskell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e5f6c043a7fc3e5a20d6df63b1fa70c4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kapilash</media:title>
		</media:content>
	</item>
		<item>
		<title>The Fourth Virtue &#8211; Virtuous Programmer 6</title>
		<link>http://kapilash.wordpress.com/2007/10/15/the-fourth-virtue-virtuous-programmer-6/</link>
		<comments>http://kapilash.wordpress.com/2007/10/15/the-fourth-virtue-virtuous-programmer-6/#comments</comments>
		<pubDate>Mon, 15 Oct 2007 07:09:22 +0000</pubDate>
		<dc:creator>kapilash</dc:creator>
				<category><![CDATA[Intro]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[tao]]></category>

		<guid isPermaLink="false">http://kapilash.wordpress.com/2007/10/15/the-fourth-virtue-virtuous-programmer-6/</guid>
		<description><![CDATA[Like his language, Larry&#8217;s virtuous programmer needs an upgrade.Apart from laziness,impatience and hubris, a good programmer should inculcate a fourth virtue &#8211; Infidelity. Infidelity towards one&#8217;s favourite programming language. One should not be too faithful when it comes to programming languages.(To use a possible mixed metaphor, you can roughly translate it as &#8221;Thou shalt covet thy neighbour&#8217;s language&#8221;. )
  I wasn&#8217;t always [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kapilash.wordpress.com&blog=1696932&post=3&subd=kapilash&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Like his language, <a href="http://www.oreilly.com/catalog/opensources/book/larry.html">Larry&#8217;s virtuous programmer</a> needs an upgrade.Apart from laziness,impatience and hubris, a good programmer should inculcate a fourth virtue &#8211; Infidelity. Infidelity towards one&#8217;s favourite programming language. One should not be too faithful when it comes to programming languages.(To use a possible mixed metaphor, you can roughly translate it as &#8221;Thou shalt covet thy neighbour&#8217;s language&#8221;. )<br />
  I wasn&#8217;t always like this. I was brought up on the shores of C where the C God was revered.There was no other God but the C God. And I was fairly happy structuring (and even object-orienting) and building my little sand-castles using those asterisks and ampersands &#8211; generally from scratch. Every one around me were honest, hard-working fishermen endowed with enormous patience and rippling muscles. I was fairly skillfull with my asterisk and was taught to always clean up after am done using it  &#8211; I was proud of many such good habits the religion gave me.<br />
 Then Java came to our scene. Like a five-star sea-front resort. With a bunch of promises &#8211; platform independance, of automatic memory management and a monopoly on the &#8216;internet-ional&#8217; market.<br />
 Although there was some initial suspicion, it was tough not to get curious about it. Sure enough, the platform independance was the real thing, there were applets, there was swing, there was networking on a totally different level, and many more. And there were no core dumps. That you don&#8217;t have to clean the mess you created did not seem that bad a habit, after all. I was soon a convert. I swore in the name of Its Holiness ,The Java Virtual Machine. I got into ecstasy everytime I wrote a class loader. Every sunday I went to church to listen to the Gang of four and their design patterns.I sincerely believed that the path to heaven was paved with eclipse plugins, byte-code engineering (<a href="http://asm.objectweb.org/">asm</a>), classloaders, <a href="http://www.eclipse.org/aspectj/">aspectjs</a>, <a href="http://www.springframework.org/">spring</a>s, <a href="http://pmd.sourceforge.net/">PMD</a>s and <a href="http://jameleon.sourceforge.net/">Jameleon</a>s.<br />
 However, all along, I indulged in perl &#8211; but it wasn&#8217;t a religion per se. I thought every one who believed in God should know how to sing in perl, so that you can actively participate in the bhajans, keertans and the choir group. I did come across some artistes par excellence who were deeply religious about Perl itself, but I believed in only the Java God and did not give perl the status of religion. However I was faithful enough about it to not to go anywhere near the Python.<br />
   I was leading such a religious and serene life when I suddenly came  to know about this enlightened one, from Japan &#8211; Ruby.<a href="http://www.smith.edu/philosophy/BodhidharmaPEW.pdf">It seemed as if, Bodhidharma came to west from the east, this time</a>.Ruby is a bubbly, charming, youthful, friendly and a humourous zen master who seemed to have an answer for every thing. He was born in Japan but seemed to have seen a lot of world already and he&#8217;s well versed in english and computer science. And is he able? Man, He could do everything a perl programmer could do &#8211; only more elegantly. And when it comes to sophistication, even Java paled before him, one has to admit. There are already a lot of people who hang around him and who consider him to be the greatest God. But he definitely seems to be one guy who should not be judged by the company he keeps. The only trouble was that, the more you interact with this guy,even on a friendly level, the farther you go astray from the Java God. Religion start looking like a foolish sentiment.<br />
 One day curiosity got the better of me, and I went to meet Ruby&#8217;s parents. His father , Mr SmallTalk, was an articulate, expressive, strong, principled and talented man who should have been a lot more famous than what he is. Probably he should have talked more.<br />
  However, it is his mother&#8217;s side that am currently obsessed with.Ruby&#8217;s mother, Lady Lisp is an elegant, rich and a very creative Goddess. Although a tad old, she is very active and has quite a few talented devotees. And she has a whole bunch of close and not-so-close cousins. Each of them is a very beautiful, skillful, talented, lovely goddess worth dying for. After a few fumbling, but nevertheless paradigm-shifting, interactions with these lovely ladies,the light dawned on me. Infidelity is a virtue.If you are too religious about your God, you may end up mastering pointer arithmetic or design patterns or GC options but may miss out on lambda calculus , Left recursion, parser combinators, side-effects.There are quite a few things a real programmer should well be aware of. (Perhaps, it gotta be: &#8220;Should be well aware of&#8221;.)</p>
<p>Object Oriented Programming (and imperative programming) is just one side of the story. On the other side of this yang, there&#8217;s the lovely Yin too &#8211; the functional programming. And both <a href="http://www.thegreattao.com/html/introyingyangtheory.html">Yin and Yang are integral part of the great Tao</a>.<br />
This site talks about my attempts at wooing some of the angels among the languages &#8211; Haskell, OCaml , Scheme, Scala and Forth &#8211; each with more Yin than Yang about them.Especially Haskell. She is pure Yin. And consequently the toughest to court. She falls for you pretty easily, if you are a PhD in computer science and if you have an especially strong fetish for obscure theories of mathematics. I am severely lacking in both these aspects, but I will try to overcome it with determination. Like all determined efforts do, this one&#8217;s going to look ugly. But who cares?. Once she&#8217;s mine, the others aren&#8217;t  going to be tough to get hold of. Be fore warned though. Am no natural cassanova.My attempts are bound to have more than a touch of gaucherie about them.</p>
<p>From my next post onwards, I will try to solve a set of problems in Haskell. Assuming I survive the ordeal, I will then attempt the same problems in OCaml,and then in Scheme, and may be in Forth too but finally in Scala. (I have a feeling that I might eventually settle down with scala but the path am choosing is probably necessary if I have to do full justice to all the features available in Scala). The  idea of this blog is to consider problems belonging to different areas of programming: parsing, string manipulation, numerical programs, web applications and ,hopefully,some aspects of parallel programming too.<br />
Come by again in a short while,to see a few programs on haskell (there wont be too much of nonsense. That I promise.)</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/kapilash.wordpress.com/3/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/kapilash.wordpress.com/3/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kapilash.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kapilash.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kapilash.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kapilash.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kapilash.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kapilash.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kapilash.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kapilash.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kapilash.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kapilash.wordpress.com/3/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kapilash.wordpress.com&blog=1696932&post=3&subd=kapilash&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://kapilash.wordpress.com/2007/10/15/the-fourth-virtue-virtuous-programmer-6/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e5f6c043a7fc3e5a20d6df63b1fa70c4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kapilash</media:title>
		</media:content>
	</item>
	</channel>
</rss>