Tower of Hanoi in Haskell

Before moving into Types in Haskell which is one big chapter in this book I am following I thought of having some more familiarization with the language.

How about solving Tower of Hanoi problem through haskell?

hanoi (0, _, _, _) = []
hanoi (n,from,to,using) =
         hanoi(n-1,from,using,to) ++
         [(from, to)] ++

Running the program for n = 3 (3 discs) and 1, 2, 3 as the labels for from, using and to towers –

*Main> dohanoi (3,1,3,2)

If you just want the number of moves in the problem, take length of the list

length $ dohanoi (3,1,3,2)

This is equal to 2 ^ n – 1.

Quick Sort – Poster boy for Haskell’s Elegance

Finally I reached to write Quick Sort code in Haskell. This code generally requires ~ 10-12 LOC in imperative languages (I implemented last in C & Perl). In Haskell (and not surprisingly) it is much lesser length and much intuitive than the pivot – if – else code. That beauty is functional programming language’s – You don’t tell “how to do” but “what to do”.

Quick Sort Algorithm is basically:

A sorted list is a list that has all values smaller than the head of the list (sorted values), then comes the head and then come all the values larger than the list (sorted values).

First take care of the edge case i.e. Empty list.

Then handle the list. Use Set comprehensions and get the list of elements < the head and >= the head and then concatenate. We have two smaller list on which the function can be applied recursively. Recursion is such a beauty.

quickSort’ :: (Ord a) => [a] -> [a]
quickSort’ [] = []
quickSort’ (x:xs) = quickSort’ [ y | y <- xs, y < x]
                        ++ [x]
                        ++ quickSort’ [y | y <- xs, y >= x]

Set comprehensions in Haskell

Remember “Set comprehensions” in Mathematics?

Being of mathematical nature Haskell provides the same kind of programming touch feel. It has a notion of list comprehensions i.e. you define a set of answers in a set notation form. For example to convey that you need a list of all integers greater than or equal to 1 and less than or equal to 100 you can write: 

[ x | x <- [1..100] ]

Here we used Range in Haskell to represent the list [1,2,3,4,..100].

A simple problem: get all right triangles whose perimeter is 24 and each of whose sides is less than 10

There is a concept of Tuples in Haskell which is very close to structures in C/C++. We can use a tuple that contains three sides and then apply the transformations (restrictions given above). First is that each side is less 10, second that it should be a right triangle and third that perimeter should be 24,

[ (x,y,z) | x <- [1..10], y <- [1..10], z <- [1..10], x^2 + y^2 == z^2, x+y+z == 24 ]

This one liner looks so cute.

Starting with Haskell

Few days back I started learning Haskell, a purely functional programming language. A functional programming language has a different paradigm altogether from the so called imperative languages (C, C++, Java, Python, Ruby, Perl etc.). Haskell is not a new language and was originated in 1987 undergoing huge changes during the course of time.

As the book “Learn You a Haskell for Great Good” mentions:

In purely functional programming you don’t tell the computer what to do as such but rather you tell it what stuff is. The factorial of a number is the product of all the numbers from 1 to that number, the sum of a list of numbers is the first number plus the sum of all the other numbers, and so on.

Haskell is –

  • Purely functional programming language
  • Lazy
  • Statically Typed
  • Elegant & Concise

I will keep writing further on Haskell and my programming experiences with it.

Compile Ruby Script To Exe (MS DOS or Windows)

Today I spent some time compiling a small ruby script of mine into an executable. Why? well, I don’t have concerns of hiding the code but this was a requirement of one of the users of my script.

I started with a Google search on such compilers. RubyScript2Exe is what I used. After installing it as a gem I got an error. I downloaded the script RubyScript2Exe.RB and tried again. But fate had it – the same error.

C:\Users\mawasthi\Desktop>ruby rubyscript2exe.rb theboringstuff.rb
rubyscript2exe.rb:621:in `replace’: can’t modify frozen string (RuntimeError)
from rubyscript2exe.rb:577:in `block in newlocation’
from rubyscript2exe.rb:505:in `block in newlocation’
from rubyscript2exe.rb:472:in `newlocation’
from rubyscript2exe.rb:505:in `newlocation’
from rubyscript2exe.rb:577:in `newlocation’
from rubyscript2exe.rb:619:in `<main>’

I read about solutions on forums. None helped. Problem was clear (some change in Ruby updated version in which program name will be a frozen string).

Then I got from one of the forums a link to another “less SEO’ed” compiler “ocra”. I installed it –

C:\Users\mawasthi\Desktop>gem install ocra
Fetching: ocra-1.3.0.gem (100%)
Successfully installed ocra-1.3.0
1 gem installed
Installing ri documentation for ocra-1.3.0…
Installing RDoc documentation for ocra-1.3.0…

Worked like charm:

C:\Users\mawasthi\Desktop>ocra theboringstuff.rb
=== Loading script to check dependencies
:: === Including 52 encoding support files (2741248 bytes, use –no-enc to exclude)
=== Building theboringstuff.exe
=== Adding user-supplied source files
=== Adding ruby executable ruby.exe
=== Adding library files
=== Compressing 5678626 bytes
=== Finished building theboringstuff.exe (1391140 bytes)

Is it possible that I call function with NULL object without segfaulting?

Oh yes it is!

While debugging my project at work I came across this interesting piece. Inspector (watch or expressions in visual studio) showed me the variable with which the function was being called was NULL (0x0) i.e. considered invalid and still the function call went fine. This variable was initialized later. I thought this should be one of the weird things that compilers and IDEs do sometimes but no it was not like that and i observed the same behavior with restarting the IDE and changing the compiler.

If your class does not have data associated with it (member variables) then its functions can be called without allocating any memory to it.

e.g. following class and example:

class A
void printA() { cout << “A\n”; }
void printB() { cout << “B\n”; }

int main ()
A * a = NULL;

Then for MS compiler cl.exe, you can call a function from a NULL object as far as you don’t access the variable even if you have defined it.

class A
int i;
void printA() { cout << “A\n”; }
void printB() { cout << “B\n”; }

int main ()
A * a = NULL;

This will SEGFAULT.

class A
int i;
void printA() { cout << “A\n” << i; }
void printB() { cout << “B\n”; }

int main ()
A * a = NULL;

and yes, you can do this in C++ and not Java.

Blank Page on install page of wordpress & resetting the forgotten root password for MySQL

WordPress installation has been painless for me always but today it got me into trouble. Well, it was not wordpress it was mysql. Well, well not even mysql me myself. I forgot the root password. Whole story here –

I was setting up wordpress. It showed me a blank page while accessing wp-admin/install.php page for installation. I was left wondering!

Then I added in wp-config.php the following line:

define('WP_DEBUG', true); // debugging mode: 'true' = enable; 'false' = disable

This enabled debugging logs and I was able to get away from the “blank page” problem. It showed the error due to which the blank page was coming. WordPress could not connect to Database.

This got me to look into phpmyadmin and that gave the issue:

#1045 – Access denied for user ‘root’@’localhost’ (using password: YES)

I had put a blank password in the configuration file and hence this error was encountered. I forgot the root password. Following solved the issue:

1. Stop the mysqld service.

2. Start the mysqld service in safe mode  and without reading grant tables

mysqld --safe-mode --skip-grant-tables &

3. Now use the mysql client to connect with the daemon and change the password

MYSQL>UPDATE mysql.user SET Password=PASSWORD(‘MyNewPass’) WHERE User=’root’;


4. Stop the safe mode daemon

5. Start the service normally.

Flex: Storing custom user strings in controls

Few days back while I was programming on Flex this cool problem came through. Problem was that I created buttons dynamically in the code based on some parameters passed to the function. These parameters would decide the label, id and color of the button. In addition to this there was an information called category which had a contextual meaning to the project I was working on. So it went something like this – 

private function InitializeAndDisplayButton(id:String, label:String, category:String)
var b:Button = new Button(); = id; 
b.label = label; 
b.addEventListener(MouseEvent.CLICK, buttonHandler);

private function buttonHandler(event:Event):void
var id:String =; 
/* how do I access “category” here */

Now the problem, how do you store the category for each button so that in the button handler you access it through the event? 

Solution I

A naive solution came to mind that I can keep a private map (flash.utils.Dictionary) between id and the category and add an entry corresponding to each id in the function InitializeAndDisplayButton and access it in buttonHandler after extracting “id”. 

Solution II – (topic of this post) 

Another solution is a cool one certainly. Function “SetStyle” takes two parameters and stores them as key-value pairs. We can use this to store any custom user strings (data) in controls. e.g. we can add following line in InitializeAndDisplayButton – 

b.setStyle(“ButtonCategory”, category); 

and access it with following code in function buttonHandler

var id:String = event.currentTarget.getStyle(“ButtonCategory”); 

This looks cool to me! 😀 


Desktop Twitter – twitter out of the browser

Desktop Twitter is an Adobe AIR desktop application written in Flex (Actionscript) which I wrote up few days back. It is an attempt to bring the twitter experience out of the browser. Current version of the application that am giving out so it contains minimal features. A screenshot is shown at left. Twitter Rest APIs are quite simple to use and developing any such application becomes painless using them.



Current set of features include –

1. On entering the user name of the user whose desk twitter page you wish to see, you get the list of thumbnails of friends of this user near the bottom.

2. On selecting any thumbnail you get to see the details of that user. Account information is shown in the right top box, twitter updates are shown in the left big box and thumbnails of the friends of the selected user are shown in the right bottom box. 

Issue Known – On scrolling the list of thumbnails fast, thumbs disappear. This is a bug with Flex and am looking around to fix this ASAP. You can workaround by scrolling really slow. 😀

Missing – Help is missing for now but will be available in next release (soon) (Details of the different panels are intended to be clear by the labels provided. ). No caching of thumbnails is done and hence sometimes there may be some delay in loading of images.

Application can be downloaded from here. You will need to install Adobe AIR runtime (takes not more than few seconds) to install (again, not more than a few seconds) and use this application. Please download the application, try it out and report any bugs, suggestions, features at

Extracting full path while uploading a file to server in Flex

In my free prototyping time I decided writing a simple uploader in AIR (what else?). I could create a working application in minutes using FileReference class and its method browse() (for opening a File Selection Dialog) and upload() method to upload the file.

But something looked odd. I wished to show the user the filepath he has selected in a disabled text box (the good old way..) but FileReference does not have the full path information. Googling helped. It said that “for security reasons full path of a file won’t be available in flash”. Valid. But then it clicked in my mind that I’m developing an AIR application. I talked to a friend, asked him for resolution. And that helped –

Use File intead of FileReference while developing AIR application. It is an extension to FileReference with more functionality (including a getter/setter to the private variable nativepath). Cool!

Thanks Raghu.