The common alphabet of programming languages

                                                                   a                                                                                    

                                    “All animals are equal, but some animals are more equal than other.”                                     “Four legs good, two legs bad.”

from Animal Farm by George Orwell

Note: This post is largely intended for those who are embarking on their journey into the world of programming. The article below highlights a set of constructs that recur in many imperative, dynamic and object-oriented languages.  While these constructs cannot be applied directly to functional programming languages like Lisp,Haskell or Clojure, it may help. To some extent the programming language domain has been intentionally oversimplified to show that languages are not as daunting as they seem. Clearly there are a  lot more subtle and complex differences among languages. Hope you have fun programming!

Introduction: Anybody who is about to venture into the deep waters of programming will be bewildered and awed by the almost limitless number of programming languages and the associated paradigms on which they are based on. It is easy to feel apprehensive of programming, when faced with this  this array of languages, not to mention the seemingly quirky syntax of each language.  Many opinions abound, about what is the best programming language. In my opinion each language is best suited for a particular class of problems and is usually clunky if used outside of this. As an aside here is an interesting link provided by reader AKS to Rosetta Code, which is stated to be a a programming chrestomathy (present solutions to the same task in as many different languages as possible, to demonstrate how languages are similar and different, and to aid a person with a grounding in one approach to a problem in learning another. Rosetta Code currently has 772 tasks, 165 draft tasks, and is aware of 582 languages)

You are likely to hear  “All programming languages are equal, but some languages are more equal than others” from seasoned programmers who have their own pet language. There may also be others who swear that “procedural languages good, object oriented languages bad” or maybe “object oriented languages good, aspect oriented languages bad”. Unity in diversity Regardless of the language this post discusses a thread that is common to all programming languages. In fact any programming language can be expressed as

Lx = C + Sx

Where Lx is any programming language ‘x’. All programming languages have a set of core, common constructs which I have denoted as ‘C’ and a set of Specialized constructs, unique to each language ‘x’ which I have denoted as Sx. I would like to look at these constructs that are common to most programming languages like C,C++,Perl, Python, Ruby, C#, R, Octave etc. In my opinion knowing these core, common constructs and a few of the more specialized constructs should allow you to get started off in the language of your choice. You can pick up the more unique constructs as you go along.   Here are the common constructs (C mentioned above) that you must familiarize yourself with when embarking on a new language

  1. Reading user input and printing to screen
  2. Reading and writing from a file
  3. Conditional statement if-then-else if-else
  4. Loops – For, while, repeat, do while etc.

Knowing these constructs and some of the basic concepts unique to each language for e.g.
– Structure, Pointers in C,
– Classes, inheritance in C++
– Subsetting in Octave, R
– car, cdr in Lisp will enable you to get started off in your chosen language.
I show the examples of these core constructs in many languages. Note the similarity between these constructs
1. C
Read from and write to console

scanf(x,”%d); printf(“The value of x is %d”, x);
Read from and write to file
fread(buffer, strlen(c)+1, 1, fp);
fwrite(c, strlen(c) + 1, 1, fp);

Conditional
if(x > 5) {
printf(“x is greater than 5”);
}
else if (x < 5)
{ printf(“x is less than 5”);
}
else{ printf(“x is equal to 5”);
}

Loops I will only consider for loops, though one could use while, repeat etC.
for(i =0; i <100; i++)
{ money = money++)
}

2. C++
Read from and write to console
cin >> age;
Cout << “The value is “ << value

Read from and write to a file // open a file in read mode.
ifstream infile;
infile.open("afile.dat");
cout << "Reading from the file" <<
endl;
infile >> data;
ofstream outfile;
outfile.open("afile.dat");
// write inputted data into the file.
outfile << data <<
endl;

Conditional same as C
if(x > 5) {
printf(“x is greater than 5”);
}

else if (x < 5) {
printf(“x is less than 5”);
}
else{ printf(“x is equal to 5”);
}

Loops
for(i =0; i <100; i++)
{ money = money++)

}

2. C++ Read from and write to console
cin >> age;
Cout << “The value is “ << value
Read from and write to a file // open a file in read mode.
ifstream infile;
infile.open("afile.dat");
cout << "Reading from the file" << endl;
infile >> data; ofstream outfile;
outfile.open("afile.dat");
// write inputted data into the file.
outfile << data << endl;
Conditional same as C
if(x > 5) {
printf(“x is greater than 5”);
}
else if (x < 5) {
printf(“x is less than 5”);
}
else{ printf(“x is equal to 5”);
}
Loops
for(i =0; i <100; i++){
money = money++)
}
3. Java
Reading from  and writing to standard input
Console c = System.console();
int val = c.readLine("Enter a value: ");
System.out.println("Value is "+ val);
Reading and writing from file
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c); } } ...
Conditional (same as C)
if(x > 5) {
printf(“x is greater than 5”);
}
else if (x < 5) {
printf(“x is less than 5”);
}
else{ printf(“x is equal to 5”); }
Loops (same as C)
for(i =0; i <100; i++){
money = money++)
}

4. Perl Read from console
#!/usr/bin/perl
$userinput =  ;
chomp ($userinput);
Write to console
print "User typed $userinput\n";
Reading and write to a file
open(IN,"infile") || die "cannot open input file";
open(OUT,"outfile") || die "cannot open output file";
while() {
print OUT $_;
# echo line read
}
close(IN);
close(OUT)
Conditional
if( $a  ==  20 ){
# if condition is true then print the following
printf "a has a value which is 20\n";
}
elsif( $a ==  30 ){
# if condition is true then print the following
printf "a has a value which is 30\n";
}else{
# if none of the above conditions is true
printf "a has a value which is $a\n";
}
Loops
for (my $i=0; $i <= 9; $i++) {
print "$i\n";
}

5. Lisp
The syntax for Lisp will be different from the others as it is a functional language. You need to familiarize yourself with these constructs to move ahead
Read and write to console
To read from standard input use
(let ((temp 0))
(print ‘(Enter temp))
(setf temp (read))
(print (append ‘(the temp is) (list temp))))
Read from and write to file
(with-open-file (stream “C:\\acl82express\\lisp\\count.cl”)
(do ((line (read-line stream nil) (read-line stream nil)))
(with-open-file (stream “C:\\acl82express\\lisp\\test.txt” :direction :output :if-exists :supersede)
(write-line “test” stream) nil)
Conditional
$ (cond ((< x 5)
(setf x (+ x 8))
(setf y (* 2 y)))
((= x 10) (setf x (* x 2)))
(t (setf x 8)))
Loops
$  (setf x 5)
$ (let ((i 0))
(loop (setf y (* x i))
(when (> i 10) (return))
(print i) (prin1 y) (incf i )))

6. Python
Reading and writing from console
var = raw_input("Please enter something: ")
print “You entered: ”  value
Reading and writing from files
f = open(filename, 'r')
a = f.readline().strip()
target = open(filename, 'w')
target.write(line1)
Conditionals
if x > 5:
print "x is greater than 5”
elif
x < 5:
print "x is less than 5"
else:
print "x is equal to 5"
Loops
for i in range(0, 6):
print "Value is :" % i 7.

R
x=5
paste('The value of x is =',x)
Reading and writing to a file
infile = read.csv(“file”)
write(x, file = "data", sep = " ")
Conditional
if(x > 5){
print(“x is greater than 5”) 
}else if(x < 5){
print(“x is less than 5”) 
}else {
print(“x is equal to 5”)
}
Loops
for (i in 1:10) print(i)

Conclusion
As can be seen the core constructs are very similar in different languages save for some minor variations. It is generally useful to get started with just knowing these constructs and few other important other features  of the language that you are trying to learn. It is possible to code most programs with these Core constructs and a few of the Specialized constructs in the language. These Core constructs are the glue that hold your code together.

You can learn more compact and more powerful features of the language as you go along The above core constructs are like the letters of the programming language alphabet. You need to construct words by stringing together these constructs and form sensible sentences which will be your program. Good luck with your adventure in your next new programming language!!!

Also see
1.Programming languages in layman’s language
2. The mind of the programmer
3. How to program – Some essential tips
4. Programming Zen and now – Some essential tips -2 

You may also like
1. A crime map of India in R: Crimes against women
2.  What’s up Watson? Using IBM Watson’s QAAPI with Bluemix, NodeExpress – Part 1
3.  Bend it like Bluemix, MongoDB with autoscaling – Part 2
4. Informed choices through Machine Learning : Analyzing Kohli, Tendulkar and Dravid
5. Thinking Web Scale (TWS-3): Map-Reduce – Bring compute to data
6. Deblurring with OpenCV:Weiner filter reloaded

The mind of a programmer

aHere is a short essay on the minds of the programmer and programming in general. Programming has been variously described as a science, an art, as black magic, as the work of craftsman etc. It is true, programming can be any or all of that described above. Programming in my opinion is going to become increasingly important in the years ahead. I would certainly advocate some knowledge and grasp of programming. There are many books that claim to teach programming anywhere between 3 to 21 days etc. This is not true. Learning to program is just the beginning of a never ending process. Here is a great piece by Peter Norvig – Teach yourself programming in 10 years.

Programming can be considered to be a language to express your thoughts on the solution to a problem. The ability to express in a programming language can vary between being simply pedestrian to being absolutely poetic! There are those who can wax eloquent in a programming language. In any case, programming is a means to an end, the end being the solution to a problem. Typically the solution to the problem, is expressed as an algorithm, which is then is coded through a programming language,. Programming can be a highly analytical and creative activity.

Programming is different from most other professions that I can think of.  To get started all you need is a computer and an Integrated Development Environments (IDE) for e.g. Eclipse, which can be downloaded for free. The IDE can be used for writing code. There are no other associated costs.

Programming is also different from other professions in the sense, that you get your response immediately.  For e.g. a painter can paint anything and imagine that he/she is the next Rembrandt or Picasso.  A guitarist can create the most hideous sound and think he is Jimi Hendrix’s re-incarnation.  Other professions like architects, civil engineers, scientists have to wait for several months to know whether they are in the right direction or not. It is not so with programming. You write code. When you compile it or execute it, the verdict is instantaneous. It is simply a “no go”, if you are wrong. There is no middle path. You are either right or you are wrong.

Having said that, I would like to look at the typical experiences of a programmer?

Tears, sweat and frustration: In the beginning programming is usually very intimidating and frustrating. In the initial stages when you grapple with the quirky syntax of the language, and try to formulate your thoughts around the problem, you will hit many speed bumps. It can be exhausting, tiring and nerve racking.  There are no shortcuts in learning how to program. You have to go through the grind, memorize certain phrases and hope that your program works.  Once you have you arms around the syntax, you are on your way to actually writing code that achieves something. Here again you will run into all sorts of problems, like loops that never end, inexplicable program crashes and mysterious run time errors etc. The early stages can be difficult and quite unforgiving. This phase requires patience to get through.

Feelings of megalomania: Someone with 5 to 7 years of programming experience knows most of the typical constructs by heart and will be able to quickly churn out programs, rather fast. This is a dangerous phase. Since you have been doing the same thing for a couple of years you are typically aware of the problems and can possibly tweak code to make it solve a slightly different problem. This is usually the stage when programmers start to experience a sense of megalomania. There are delusions of grandeur. You may remember the programmer shown in Golden Eye who keeps saying “I am invincible!” whenever he is able to solve a knotty problem. These programmers have the feeling that “Nothing is impossible”

Programming is a great leveler.  Programming can be a great boost to your ego. When you are able to visualize a problem, strategize the solution and actually get it to work, it does wonders to your ego. Programming can really boost your self-esteem. But you should not just stick to your comfort zone and write code in exactly the same language in exactly the same domain.  It really helps to move to a different language, preferably a different paradigm – for example a move from procedural (C) to Object Oriented (Java, C++) or from object oriented to functional (Lisp, Haskell). Similarly moving from Web programming to protocol design or from data communication to app design will do wonders. The shift to a new programming paradigm and new technical domain will put you on even keel. All your knowledge and expertise will evaporate when you move to a new domain. Moving around in technology will keep you more grounded. You will realize that there is still so much more to learn. There is yet another universe.

In other words, programming keeps you honest!

My journey of 25+ years as a programming has helped me to learn technology in all its flavors. More importantly I was able to learn about myself. I have seen it all. Sweat, tears, frustration, fear, anger, pride and ecstasy.

.

A few years back, once you learned the basics, if your work did not involve coding, there was not much to do. But these days you can really do some fun things. You can imagine any app you want and actually start to realize it. Who knows, your app may be the next block buster! I am certain all of us have ideas which we want to implement. Programming allows you to just that!

Programming really makes you exercise your grey cells. Who knows we will soon hear that research has proved that programming helps prevent Alzheimer’s and Parkinson’s disease.:-)

In any case, learning to program is one good thing.

Also see
1. Programming languages in layman’s language
2. The common alphabet of programming languages
3. How to program – Some essential tips
4. Programming Zen and now – Some essential tips -2 

You may also like
1. A crime map of India in R: Crimes against women
2.  What’s up Watson? Using IBM Watson’s QAAPI with Bluemix, NodeExpress – Part 1
3.  Bend it like Bluemix, MongoDB with autoscaling – Part 2
4. Informed choices through Machine Learning : Analyzing Kohli, Tendulkar and Dravid
5. Thinking Web Scale (TWS-3): Map-Reduce – Bring compute to data
6. Deblurring with OpenCV:Weiner filter reloaded

Find me on Google+

Programming languages in layman’s language

There is such a wide variety of programming languages that there is always confusion as to why there is such a profusion of languages. Different programming languages solve different classes of problems. Programming languages can be classified broadly into the following 4 classes.

Procedural Languages: In these languages one thinks in terms of the sequence of steps to solve the problem. It could be thought of solving the problem in 1st person and then substituting the “I” with “the program”. So for example in procedural language we could think

I will wake up.
I will brush my teeth
I will open fridge
I will take milk
I will warm milk

So in procedural languages actions are performed sequentially to achieve the desired end result.

Examples: FORTRAN, BASIC, Pascal, C

Object Oriented (OO) Languages: When a problem is solved using Object Oriented techniques we look at the world objectively. So we need to first identify the participants and functions performed by each of these participants. So the above situation would be viewed as

I, Fridge, Microwave – Participants

then we need look at what functions the above 3 will perform
I – wake up, brush
Fridge – Open door, close door
Microwave – Warm

Hence in OO languages the problem is solved as the interaction of functions between participating objects.Examples: C++, Java, Smalltalk, C#

Both procedural and OO languages are compiled languages and are also known as “Imperative Languages”. A useful analogy is to view compiled programs as mashed, pre-cooked food that can be easily assimilated by the digestive system or the raw hardware.

Dynamic Languages: Here these languages are either interpreted or converted to byte code. Interpreted languages are similar to raw & uncooked food which must be crunched, munched and digested on the fly. However these languages include in themselves many, many features that are commonly used. While the first two would just specify the method, dynamic languages include several specific features as functionalities. To use an analogy while in the above 2 programming language types one would set the time and the power level for each item to heat in a microwave, dynamic languages come with readymade buttons for those frequently used.

I – wake up, sleep, eat, drink, wash etc
Fridge – Cool, refrigerate, thaw, and freeze
Microwave – Heat popcorn, frozen food, meat etc

Since you get a lot of stuff for free and the program is interpreted on the fly Dynamic Languages take a lot more time

Examples: Perl, Python, Ruby

Functional languages: Here we think in terms of functions that are performed on items. They can be performed on any object.

For example the above problem would be viewed as the following main functions
E.g. Wake, sleep, warm, thaw, heat, cool, freeze.
We then take and apply the function ‘warm’ on the ‘milk’
Heat on ‘vegetables’  etc

In Functional Programming functions invoke other functions to accomplish a task. The problem is solved from the inside-out. In Functional languages like Lisp one starts with some core functions and build layers over it. For e.g. in a functional language we would express calorific energy as

metabolize (assimilate (digest (chew (food))))

Examples: Lisp, Clojure, Haskell, Erlang

Each language is best suited for only certain applications. So just like it is inappropriate to use pliers where an Allen wrench would suffice we need to know which language is most suitable. If we know what the class the problem is and the performance we want we can choose the appropriate language

Find me on Google+