My first foray into Google Go, and a URL shortener

I’ve been interested in Google’s Go for a while now. It feels like one of those new languages that are very promising and are here to stay. Certain developers I look up to in the community have also been talking about how Go is great for concurrency and a great language to work with in general.

So far I’m only done with An Introduction to Programming in Go (a short, free, online book), and halfway through Go by Example, but it was enough for me to start creating toy programs of my own. There’s a lot more to read and learn in Go – but I recommend both of the above resources as quick getting started guides for intermediate programmers.

I’ve also been interested in expanding my horizons a bit more than the day to day of my day job, so I was wanting to explore a new algorithm, say, e.g. a URL shortening algorithm. I found a good explanation on StackOverflow, so I decided to give it a go.

Here is the result. It’s a very primitive piece, to be sure, and it can be improved in a gazillion ways. I’ll be sure to check back as I learn more Go and more effective Go, and will be adding to both the functionality and cleanliness of the code. For now, I’ve crafted some functions at best, that try to create maps between digits and letters, and do some division and string concatenation, and that’s pretty much it for now. Maybe there’s a lot better way of creating the alphabet map than the way I’m doing it. But it does seem to get the job done for a given alphabet.

Finally, I’d like to say that I’ve really been liking Go so far. It feels like a cleaner C. It has some aspects of more modern programming languages too, e.g. interfaces. But it has no classes, only structs. It also seems to be a simpler language, e.g. it doesn’t confuse you with three to four different ways of constructing loops – there’s only for, nothing else. I like the panic and defer mechanisms, and I also like goroutines and channels. I’m not the most experienced person when it comes to concurrency, but so far it has been a pretty smooth ride for me, with no surprises (well, only pleasant ones). Go is also more powerful than a lot of other languages out there in terms of memory management – it combines the best of two worlds – it has garbage collection, but it also provides you pointers. A great language overall, I must say.

I’d just use Vim for everything whenever possible. Most of my Go adventures have also been in Vim – there are some plugins out there that make it easier for you to import stuff, but I haven’t tried any plugins so far apart from color coding. I’ve had a brief stint with the LiteIDE – it’s not bad – it does a fantastic job of performing Intellisense of sorts, but the visuals are not the greatest (I believe it’s Qt-based), nor the shortcuts or text-editing shortcuts impressive. I’d use it if I must, but I can stick with Vim otherwise.

I have a feeling that there’s going to be more to come from me in GoLang. Here’s something funny to keep the spirit up 🙂

Python vs C# – an incomplete comparison

This is not going to be a complete comparison of everything that the two languages have to offer, but a beginner’s first look at how the two languages look and feel different. Expect a lot of additional posts on additional differences and similarities in the future.

Apart from Python being dynamically typed, interpreted and C# being statically typed, compiled, here are some subtle points of interest:

1. In C#, you can use {0}, {1} etc. as placeholders for variables in a format string, in a Console.WriteLine() function call, and the format string is followed by a comma separated list of the variables used. In Python (in Python 3 that is, not in Python 2), you do that by calling the method format of a string object, which has the {0}, {1}, etc. embedded, and the string is therefore followed by a dot, which is followed by the keyword format, parentheses (hence, a tuple) containing all the variables.

2. In C#, using the directive using <namespace name> is sufficient to include everything from the corresponding namespace into the current file. In Python, even after you use import, you need to qualify the name of the corresponding entity with the name of the namespace, e.g. random.randint(). If you want to avoid doing that, you may either do from module import *, or from module import entity. You may use something like System.Console.WriteLine() in C# without saying using System, but you cannot do something like that in Python.

3. In C# there are no performance differences whichever variant you use. I am not sure what happens under the hood in Python. I will have to get back to you on that one.

4. In Python, once you install a module, you can import it easily from anywhere. In C# on the other hand, some assemblies (read, modules for all practical purposes), are located in different directories and the compiler will need to be told explicitly about that.

5. Being a compiled language (with a compiled bunch of files called an assembly), C# (or any .NET language, for that matter) gives rise to things like the IL (CIL or MSIL), metadata, manifest, and by extension assembly viewers (disassemblers), decompilers, etc… we don’t have these problems in Python. Python does have py2exe which generates a compiled executable for the Windows platform. However, py2exe apparently only keeps the byte-compiled version of the code and not the raw one, so as it appears right now, it might not be that straightforward to get your raw Python source code back if you only have the compiled version. In a C# assembly, you can get back to the actual code by using decompilers, e.g. Reflector.

That’s all for now.

PS: WordPress, please allow using C# as a tag, don’t automatically convert C# to C++ !! For now, I am using C-sharp as the tag:-)

Interesting differences between Python and C++

This is not a post about praising or bashing either language, but rather an objective account of the differences I discovered myself while working through the Invent With Python book. These seem interesting to me, so here goes:

[1] This is still a bit fuzzy to me, but in Python, variables are in scope even outside the loops in which they are first instantiated. True, we do not need to declare variables in Python, as opposed to C++, but intuitively I would still have thought that a variable won’t be visible or retain its value outside the loop it is first used in. However, as the screenshot shows, Python recognizes the variable r outside the for loop in the function and returns it. C++ however, throws a compile time error when it sees the code in the corresponding screenshot.

Python recognizes variables outside the loop

Python recognizes variables outside the loop

C++ does not recognize variables outside the loop

C++ does not recognize variables outside the loop

[2] In Python a function may accept an argument of any type, and return a value of any type, without any kind of declaration beforehand. For example, in the screenshot, you see the function might accept a boolean and return a boolean, or it might accept an integer and return a string or vice versa. Even though Python is strongly typed in a sense that you may not add a string and an integer without an explicit conversion. For example in Perl, something like this is valid:

Multiple argument- and return-types in Python

Multiple argument- and return-types in Python

my $a = “A”;
my $b = 3;
my $c = $a.$b;
print $c.”\n”;

And it produces the result A3. However, you may not do the following in Python:

>>> a = ‘a’
>>> b = 3
>>> c = a + b
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
TypeError: cannot concatenate ‘str’ and ‘int’ objects

Yet this kind of flexibility that Python provides in calling functions and returning values makes our code incredibly simple and much more maintainable. Perl provides something like that too but Python looks cleaner, is object oriented, and still maintains a little strictness about types. Again, this post is not about bashing a language or promoting another.

[3] The division of two integers in Python is always a float (in Python 3; or in Python 2 if you import division from __future__), as opposed to C++ where you need to do some casting to make that happen.

[4] The round function in Python always rounds intelligently – round(4.3) is 4 and round(4.9) is 5, and it even works for negative numbers. In C++ there’s no round function; there’s floor and ceil, but you need to know beforehand which one to use.

Floor and ceil functions in C++

Floor and ceil functions in C++

Pass by value or reference in Java

Something to keep in mind for programmers coming from a C/ C++ background who ‘grow up’ reading and learning about pass by value/ pass by reference of variables between functions – what happens in Java is a bit different from either of these paradigms. Consider what happens when the main method is called in the following Java code:

Java pass by value or reference

Java pass by value or reference

Can you guess what the output is?

The output is an array of 1’s, not an array of 0’s or 2’s. If the pass were by reference, then any changes made in the function test would be reflected in the main – meaning an array of 2’s would be printed. But this is not what happens. If the pass were by value, then an array of 0’s would be printed, because no matter what you do in test, the array will have a local value there and would not be reflected in the main, which will in turn retain the value the array was initialized with. So what is going on here? Why do we get an array of 1’s?

In Java, there are a handful of things to keep in mind:

  1. You can only pass by value
  2. Arrays are objects
  3. No objects are ever passed
  4. References to objects are passed by value
  5. References are pointers under the hood – Java does have pointers after all
  6. Objects can only be manipulated by references

Point number 4 is the most important one. The value of the reference to the array is passed to test – which means if you change the value of the array pointed to by the original reference within the called function, the change will reflect in the calling function. But you can’t make the reference point to something else in the called function, because you only have the value of the reference in the called function, not the reference itself.

For primitive types, however, i.e. if we were to talk about an int, for example, the value in the called function will be a copy of the original, and any changes made in the called function to that primitive type value will be local to the called function, and will not be seen in the calling function at all. This is why some people call Java impurely object oriented, because it allows the concept of certain things, i.e. primitive types, which are not objects, as opposed to purely object oriented programming languages like Python and Ruby where everything is an object.


Sudoku solver using recursive backtracking

Inspired by a video lecture from Stanford University about recursive backtracking and how it can be useful, I sat up all night to write my own recursive backtracker to solve Sudoku’s. You can see it here. The video lecture presents a pseudocode in C++, and there is little to no emphasis on the code itself. While writing the code in Java, I ended up having to make a lot of design decisions, and when it eventually ‘clicked’, I had an ‘aha’ moment. So you can try to download the code, follow the instructions, make it solve a Sudoku of any level of difficulty, and try to break it. Just a little caveat – if you give it an evil or diabolical Sudoku, you will have to increase the stack size of your JVM [up to 50m].

Have fun!

Beautiful code

What makes code beautiful? What makes it ugly? What makes it pleasing to the eye? What makes it an eyesore?

What is beauty to you? Is your wife beautiful? Are your children beautiful? Those flowers, that sunrise, that ocean, that chiseled muscular physique on that model or sports(wo)man – are they beautiful to you? Maybe yes. But why? Can you explain it?

I am by nature an aesthete, and for me things have to look pretty. I would say what makes things pretty is if they perform what they are meant to perform, and it makes them visually appealing if they have the right proporions – you know, not too fat, not too thin, not too short, not too tall. Just like the golden ratio governing the proportion between several body parts or other natural objects. You’d think when it comes to code, similar principles should apply, right?

Well, you will be right. And maybe many of us do it instinctively. But many of us probably also do it subconsciously and don’t really think about it. This talk here will probably shed some light on the concept. I am not too impressed by the depth of the talk, yet it is a topic that should be at the back of every programmer’s head, if only for the reason that keeping code clean and pretty will make it easier for you to edit or modify or even understand it later.