Writing “Hello World” program!

Sometimes we get questions which are silliest but have to attempt since the situation demands it (interviews, presentations, professor’s lecture..). One of those silly (of almost “0” importance and usability in life) questions is “How many ways can you write a ‘Hello, World!’ program in C/C++?”.

For those, who want me to write some specification of the program – task is to write a program to print on console a string “Hello, World!”. Well, lots and lots of answers —

int main() { printf(“Hello, World!\n”); } /* C Example */

int main() { std::cout << “Hello, World!” << endl; } // C++ Example

int main() { if(printf(“Hello, World!\n”)) {} } // C; without semicolon

int main() { while(!printf(“Hello, World!\n”)) {} } // C; without semicolon

following, I came through while re-reading stroustrup is writing a program using iterators (Chapter3;Iterators and I/O). This is nothing new and just a iteratorized manifestation of example II above.. but yes, different clothing!

ostream_iterator<string> oo(cout);
int main() { *oo = “Hello, “; ++oo; *oo = “World!\n”; }

Advertisements

Modifying built-in classes

Inheritance is a powerful idea in object oriented programming. This lets you add new enhancements to existing classes. Well, not exactly. You have to create a new data type derived from the existing classes and use these for additional enhancements.

For example, if we want to add a function palindrome to String class. Solution existing in all (most?) object oriented programming languages is to create a class say Word derived from String and add the function to this class. In Ruby for example it would look like:

Note – replace ‘LT’ with corresponding symbol for less than. HTML is messing it up and I feeling lazy to find the &; version for it.

 
 
class Word 'LT' String 
def palindrome? 
   self == self.reverse 
end
end 
... 
irb> w = Word.new("level")
irb> w.palindrome? 
true
irb> w1 = Word.new("simple")
irb> w1.palindrome? 
false 
 

What we lose here is that we CANNOT call the function on String objects e.g., following is invalid:

 
irb> "level".palindrome? 
NoMethodError: undefined method `palindrome?' for "level":String
 

Ruby, quite surprisingly (and did i mention it never fails to amaze!) provides this. It lets you modify the built-in classes. So we can add a function simply by following:

 
 
class String 
def palindrome? 
   self == self.reverse 
end
end 
 

and it gets your String more powerful!

 
 
irb> "level".palindrome? 
true
 

Isn’t that coooooool??

Facebook open sources its C++ library

Facebook has announced to open source its C++ library named folly and made it available via Github.

Library is C++11 Components and is claimed to be highly usable and fast. In fact, their introduction page particularly focuses on the performance part of the library. Folly has been tested with gcc 4.6 on 64 bit installations.

I just downloaded the library for a quick look and it should be interesting to peek into the code.

You can also have a look here: https://github.com/facebook/folly/blob/master/folly/docs/Overview.md

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)] ++
         hanoi(n-1,using,to,from)

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)
[(1,3),(1,2),(3,2),(1,3),(2,1),(2,3),(1,3)]

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.

Orthogonality and its importance in software development

I’ve been lately reading The Pragmatic Programmer by Andrew Hunt & David Thomas. Been onto a chapter about decoupling requirement in the development of software, I thought of putting few lines on the weblog. Orthogonality is derived originally from Geometry where it is meant to illustrate two lines which meet at right angles and hence are mutually independent moving in all directions. In software, orthogonality refers to the independence between the modules of the software. e.g. user interface of a software should not have any dependence on Database schema. Decoupling, if not met properly while designing software, can lead to disaster in code maintenance. A decoupled code is better for maintenance because of numerous reasons –

1. Changes are localized and hence development and testing time (and cost) are reduced. Quality also improves since better division of work is possible.

2. Problems are also localized. An issue in one module does not affect other modules and hence fix requires to be done their only (or whole module can be replaced by another implementation altogether).

3. There is more possibility of smaller independent teams (which is ideal for a better coordination)

An interesting introduction into orthogonality is the advent of Aspect Oriented Programming (AOP), a research project at Xerox Parc. As Object oriented programming focusses on the objects and their interaction, Aspect oriented programming focusses on aspects (concerns). AOP lets you express a behavior which would otherwise be distributed throughout the source code. The most obvious example would be logging. Log messages are normally generated by sprinkling explicit calls to some log function throughout the code. With AOP, you implement logging orthogonally to the things being logged. Using the AOP for Java, you could write a log message while entering any method of Class Fred by coding the aspect –

aspect Trace {
advise * Fred.*(..) {
static before {
Log.write(” -> Entering ” + thisJointPoint.methodname);
}
}
}

If you weave this aspect in your code then log messages will be generated and if you don’t, they won’t. Either way, your original source is unchanged.

Towards the end of the discussion is a challenge: Consider large GUI-oriented tools typically available on Windows and small but combinable command line tools used on shell prompts. Which do you think are more orthogonal in design?

What do you think?