The Curious Schemer

The following sentence is false. The preceding sentence is true.

Archive for May 2007

10 Eclipse Navigation Shortcuts Every Java Programmer Should Know

with 129 comments

Man, I’m such an impatient guy. I cringe whenever I see somebody squint and frown, looking for a JSP file in Eclipse by browsing painfully through the gazillion JSPs in multiple folders in the Package Explorer. I squirm whenever I see somebody looking for a Java class by clicking through packages, one by one, backtracking if it’s the wrong package, and so on, until he sees the correct Java class.

I mean, any resource in the workspace is literally seconds away. Ditto to classes (and interfaces, and members, and so on). Why waste time and brain cycles to wade through countless lines in countless files? I thought that every Eclipse user knows this, in fact, if you’re reading this, most probably you already know this too. But thousands of Eclipse JDT users who never bother to read tech blogs in all probability will also never bother to find out what Eclipse can do for them. And it’s a pity, really, because they’re really missing out a lot. So maybe if you know one, you can forward this to them or something. Make them more productive or something, ya know. 30 seconds saved for every file can add up to really a lot!

So without further ado, let’s say you want to:

  • Open any file quickly without browsing for it in the Package Explorer: Ctrl + Shift + R. This shortcut opens a dialog box that accepts the name of the file you’re looking for. It even accepts wildcard characters, yo. Typing *-conversion.properties will give you the list of all files that ends with -conversion.properties. So everytime you want to open a file–stop that hand from going to the mouse, and press Ctrl + Shift + R instead!

Opening a resource in Eclipse

  • Open a type (e.g.: a class, an interface) without clicking through interminable list of packages: Ctrl + Shift + T. If what you want is a Java type, this shortcut will do the trick. Unlike the previous shortcut, this even works when you don’t have the Java source file in your workspace (e.g.: when you’re opening a type from the JDK).

Opening a type in Eclipse

  • Go directly to a member (method, variable) of a huge class file, especially when a lot of methods are named similarly: Ctrl + O. Say, you’re browsing through a file which has 500+ lines of code. How do you look for a method? Don’t use Ctrl + F and then type the method name. Use Ctrl + O, which gives you a list of candidates that match what you’ve typed so far. Select the member you want using the arrow keys, and press Enter. (Alternatively, if you just want to jump from one member to the next (or previous), you can use Ctrl + Shift + ↓ or Ctrl + Shift + ↑, respectively.) UPDATE: As Nick pointed out in the comments section, pressing Ctrl + O again shows the inherited members. Thanks Nick! :)

Browse Member

ctrl_o_2.jpg

  • Go to line number N in the source file: Ctrl + L, enter line number. Of course if the stack trace is in the Eclipse console, you can just click the hyperlink. But if it’s in a log file or something, just use this shortcut to go to the line in a jiffy.

Go to a line number

  • Go to the last edit location: Ctrl + Q for . If you have a big file, it’s annoying to jump from one location in line 1000+ to 2000+ only to realize after looking at line 2017 that you’ve made a mistake in that location near line 1000+ just now. This shortcut brings you right to where you last edited a file. Very handy in a big file. Gone are the days of “let’s see… where did I edit it again… nope, nope… ah there it is”. (This even works when you’re already looking at a different file.)
  • Go to a supertype/subtype: Ctrl + T. Before I found this, if I want to go to the superclass of a class, I’d go the the very top of the file, hover my mouse over its superclass, hold Ctrl, and click. Disgusting. Now I just press Ctrl + T and I get this dialog below, which toggles between supertypes and subtypes when you press Ctrl + T again.

Subtype hierarchy view

Supertype hierarchy view

  • Go to other open editors: Ctrl + E. I know you can cycle through the editors using Ctrl + F6 as well, but I prefer Ctrl + E because Ctrl + F6 has this annoying behaviour of requiring you to keep the Ctrl key down, and the distance between Ctrl and F6 is so far I have to twist my left hand to do that. Just press Ctrl + E, and either use the arrow buttons, or type the name of the file you’re editing.

Open editor

  • Move to one problem (i.e.: error, warning) to the next (or previous) in a file: Ctrl + . for next, and Ctrl + , for previous problem. No need to lift your hands off the keyboard to click on that red or yellow stripe.
  • Hop back and forth through the files you have visited: Alt + ← and Alt + →, respectively. I have to admit I don’t find myself using these two often, though.
  • Go to a type declaration: F3. Alternatively, you can hold Ctrl down and click the hyperlinked variable or class or whatever it is the declaration of which you want to see–but why lift your hand off the keyboard? Just press F3 and Eclipse will bring you to the declaration of whatever is at the cursor at that moment.

OK, that’s it for this post. There are tons of other Eclipse shortcuts not covered by this article. To see the whole list, just open up your Eclipse (I’m assuming Eclipse 3.2 here–in older or more recent versions this may differ slightly), go to Help → Help Contents → Java Development User Guide → Reference → Menus and Actions. The whole motherload is there, from generating comments, correcting indentations, surrounding with, and so on.

The point I’m trying to get across is: Eclipse has a LOT of shortcuts to make things real easy for you. Java (or heck, any software) development is hard. We shouldn’t make it harder on ourselves by fighting our tools! Let our tools help us as much as possible, so we all can go back on the dot and spend more time with our family, lovers, or whatever it is we want to spend more time on. There’s no honour in working hard inefficiently. Only disgrace.

Written by rayfd

May 20, 2007 at 6:22 am

Posted in Java, Technology

The Truth About Positive Thinking

with one comment

I always cringe when positive thinking gurus go around telling people, “There are no limits! You are only limited by your own thoughts! You can do anything and achieve anything as long as you think you can!”

Because I, the skeptics, and the negative thinkers know, that the world doesn’t work that way.

For instance, I know that no matter how hard I train, how many techniques I practice and drill to perfection, how determined and positive I am, I’ll never be able to beat Mike Tyson at his peak (heck, or Mike Tyson NOW) at boxing. My talent, my muscularity, my reaction time to evade and time punches, and so on, are simply not there. If I have to beat Iron Mike in something, I’ll choose writing software. Somehow I’m quite confident I’m better than him in that one.

Similarly, no matter how correct their diet, how spotless their routines, how flawless their lifting techniques, 99.9999% of the guys out there will never have biceps as big as Arnold Schwarzenegger’s. Their genes simply don’t permit that. Whereas the ones with the right genes go on to become the next Ronnie Coleman or Dorian Yates.

Have you ever tried so hard at something, only to see a “natural” breeze through all your obstacles in a tenth of the time you needed to get through them? Of course you have. It’s annoying, I know. But that’s also a fact of life. I think an important part of growing up is finding out that you WILL find a ceiling, and be OK with that and accept that. But an even more important thing is to really find out whether the ceiling you are seeing and hitting against is your true ceiling, your true limitations, or a false, fake, self-imposed ones.

That, is the truth of positive thinking. To find out your true ceiling. It is NOT true that there are no limits. That’s bullcrap. Everybody has limitations. But you’d better be damn sure that you’ve developed yourself to your own full potential, instead of hitting a ceiling that is put there by your insecurity, your fear, your laziness, your negative thinking, or whatever.

This can be quite disheartening at first. Because if you’re like most people, as you grow up, you get to witness your (perhaps unrealistic) childhood dreams being shattered one by one. And in the process, it’s easy to fall into the so-what’s-the-point-I-might-as-well-stop-improving-right-now thinking pattern.

Why do you think parents are so often charged guilty of telling their children to be “realistic” and to “forget their big dreams”? Because 99.9999% of the parents have gone through this before. Only 0.0001% have continued to develop themselves and find that their limits are higher than everyone else in the world–they become Olympian gold medalist, world-class musicians, Tiger Woods, Warren Buffett, and so on.

In fact, before I figured this out, I used to be quite negative about this whole thing. I used to think: what’s the point of even trying when the best I could ever do, to my full potential, is most probably only mediocre?

And now I think I have the answer.

  • Cos until you’ve tried it and do it to the best of your ability, you won’t know. In all probability your true ceiling might be the highest in the world. You might be world-class at something, you just don’t know it yet. Say, can you memorize the first 21 digits of Pi? Then you’re already world-class.
  • You keep doing it because you like it, even when you’ve found that you’re far from world-class level. I love programming, and it’s something that I’ll still do when I’m 60. Even if I’ll probably will never be the world’s best programmer. But I don’t care. I like it.

(Or probably I am the world’s best programmer. Since I’m so humble.)

So what the heck are those positive thinking, supposedly self-improving gurus are for? The good ones help to find out your true capacity. Because I suspect we never really get to know how high the true ceiling of our potential really is. It’s not limitless, surely. But it may also be much higher than we’ve ever dreamed of. And we need the gurus to lie to us and keep telling us there’s no limit so we won’t stop until we’ve hit our real limit. And that probably means that we shouldn’t stop, ever.

Written by rayfd

May 13, 2007 at 1:11 am

Posted in Mind, Technology

Y Combinator for Dysfunctional Non-Schemers

with 20 comments

A lot of software developers don’t come from a Computer Science background. I think in the long run this doesn’t matter, since I’ve seen a lot of CS grads who have completely forgotten things that are supposed to set them apart from the rest of us (“Lisp? You mean that AI language with a lot of parentheses? Yeah I used it before in uni. So?”). Besides, a lot of CS grads can’t program anyway. Plus, if one really cares about the programming craft, during his/her journey of ever improving his/her efficiency and effectiveness as a software programmer, one tends to come full circle and go back to the root, which is made of the stuff CS grads are forced to read about in university.

Now one of the thing that I find really interesting, yet had baffled me for a long time, is the Y Combinator (no, not Paul Graham’s company). Maybe CS students eat Y Combinator for breakfast. But I graduated as an electrical engineer. It’s only recently, when my programming self-improvement routine brought me to study Lisp, Scheme, and recursion in greater details, that I came across this strange Y thing that so many very smart people, like this guy, this guy, and this guy have written about. Before this I’ve never heard of it in my life. It’s like I’m trying to digest what I think is a very cool and profound concept, and then I come across these mental landmines like “pass the function as the first argument to itself”, and my brain will just explode and I have to restart all over again.

What is Y Combinator, exactly? Why does it work? I do real-world applications in Java/C#/C++/JavaScript or whatever, I don’t do Scheme for a living. What’s in it for me? Is it just a cool idea with no practical applications whatsoever? I find that the best way for me to understand something is to write about it. So here it is.

JavaScript: Lisp in C’s Clothing

All examples will be in JavaScript. Examples in Lisp/Scheme can be difficult to read, especially when you’re not used to the language yet. Writing the examples and illustrations in the familiar C-syntax will make it easier for me (and you, if you’re one of the two or three people who are reading this). The examples won’t be in Java, because Java’s obsession with nouns will make it awkward to write them. The fact that functions are first-class in JavaScript makes things a LOT easier. (If you need a short intro of JavaScript’s true capabilities, I’d shamelessly recommend this article.) So, with that out of the way, let’s start!

The Problem

Let’s start by a simple basic recursive function: factorial. Simplest function in the world, right? It’s like the Hello World of recursion.

function factorial(num) {
    if(num < 2) {
        return 1;
    }
    return num * factorial(num - 1);
}

Of course, functions are first-class in JavaScript, so we could’ve written it like this:

var factorial = function(num) {
    if(num < 2) {
        return 1;
    }
    return num * factorial(num - 1);
};

But now we have a potential problem, don’t we? The recursive call to factorial within the method only works because we happen to name the variable “factorial” as well. Should we name the variable differently, say, “fact”, instead of “factorial”:

var fact = function(num) {
    if(num < 2) {
        return 1;
    }
    return num * factorial(num - 1);
};

Then we get an error, because when we call “factorial(num – 1)”, the name “factorial” is not bound to anything. We can fix it for this case by changing the call to “fact(num – 1)”, of course, but this approach is a quick fix that doesn’t work, because this function can be assigned to any variable of any name.We have a problem that can be summed up thus: a recursive function is a function that calls itself. But an anonymous function has no name. So… how is it supposed to call itself for recursion?

First Attempt

(If you’re thinking: “Just give the bloody function a bloody name so you can make it recursive and get on with your life!”, I can’t say I totally disagree with you at this point. But anyway.)

So what can we do here? Well for one, we can keep the function anonymous, and get the name for recursion from a parameter passed to the anonymous function, like this:

var fact = function(forRec, num) {
    if(num < 2) {
        return 1;
    }
    return num * forRec(forRec, num - 1);
};

Then when we want to use it, we just pass the name of the function to itself, like this:
js> fact(fact, 0)
1.0
js> fact(fact, 1)
1.0
js> fact(fact, 2)
2.0
js> fact(fact, 3)
6.0

No matter what the name is, as long as we keep passing the same name as the first parameter, we’ll be OK–the anonymous function will be correctly calling itself.

But… OK, Second Attempt

The solution kinda works. But it’s not nice, requiring your users to your function name twice everytime they want to use it. Besides, now the code becomes less clear–everybody knows factorial, but this self-passing-to-self business is obfuscating the code. I believe we can do better. Let’s try to separate the “passing a function to itself” bit from the “calculate factorial of” bit, by currying it. Like this:

var createFact = function(forRec) {
    return function(num) {
        if(num < 2) {
            return 1;
        }
        return num * (forRec(forRec))(num - 1);
    };
};

(Currying, or Schönfinkelisation, is a lesson to all of us to choose names that are easy to spell, remember, and pronounce. Or else you may invent something and the other guy with the catchier name–who can compete with Curry?–gets the credit.)In the snippet above, the outer anonymous function (the one with forRec as a parameter) returns another anonymous function (the one accepting parameter num). The latter is very similar to our original factorial function (remember that our objective is to separate the passing-function-to-itself bit from the factorial bit), except for the bit in green:

(forRec(forRec))(num - 1);

That line is where the inner function needs to recurse. But instead of requiring a name to recurse, it calls the outer function… which returns the inner function itself. And that returned inner function is in turn called, with “num – 1″ as its argument. There we have our recursion.So now we have a slightly cleaner solution. We can use the outer function to create the inner function like this:

js> var factorial = createFact(createFact);
js> factorial(10)
3628800.0

Note that this is equivalent to this one-liner:

js> createFact(createFact)(10)
3628800.0

Hmmm. The code for the factorial function is still polluted, though. Let’s try to take out the anonymous recursion part from the factorial function entirely.

Third Attempt: Wrap, and wrap, and wrap, and wrap…

Our second attempt is still not as clean as we want it to be. Ideally, we want to separate the part that takes care of the anonymous recursion, from the part that actually does the factorial computation. Let’s see our last function again:

var createFact = function(forRec) {
    return function(num) {
        if(num < 2) {
            return 1;
        }
        return num * (forRec(forRec))(num - 1);
    };
};

The only difference between the inner function and a typical factorial function is the recursive part. Let’s try to take that forRec(forRec) bit out–that is, instead of doing it inside, let’s see if we can do it outside and pass it in as a parameter. Here’s the function again, with the forRec(forRec) taken out of the picture:

var fact = function(rec) {
    return function(num) {
        if(num < 2) {
            return 1;
        }
        return num * rec(num - 1);
    };
};

And like I said above, we do the forRec(forRec) outside, and then pass it to the fact function:

var recur = function(forRec) {
    return function(n) {
        return fact(forRec(forRec))(n);
    }
};

Then we use it like this:js> var factorial = recur(recur);
js> factorial(6)
720.0

Or, as we’ve seen above:

js> recur(recur)(6)
720.0

Did you follow what happened during the recur(recur) call this time? From recur’s definition, a call to recur(recur) returns an anonymous function like this (substituting the parameter with the actual argument):

function(n) {
    return fact(recur(recur))(n);
}

Let’s see what happens when this anonymous function is called: it returns the result of calling fact(recur(recur)) with argument n. Now what does fact(recur(recur)) evaluate to? If we go back to the definition of fact, it returns the following anonymous function:

function(num) {
    if(num < 2) {
        return 1;
    }
    return num * recur(recur)(num - 1);
};

which does the actual computation of the factorial. And when we reach this line:

return num * recur(recur)(num - 1);

We see that we have recur(recur). Which we have shown above, to eventually evaluate back to this factorial-computing anonymous function itself. In other words, it is calling itself. Ladies and gentlemen, we have recursion!

Okay… So What?

Indeed. So what? In the last attempt, we still have to call recur(recur) before using it? Well, the difference is that we have separated the anonymous recursion mechanism from the factorial logic. So for instance, instead of hard-coding the call to fact inside recur, we can make it a parameter, like this:

var recurWrapper = function(f) {
    var recur = function(forRec) {
        return function(n) {
            return f(forRec(forRec))(n);
        }
    };
    return recur(recur);
};

Then we can use it like this:js> recurWrapper(fact)(6);
720.0

Eh, that’s better! No more of this passing self to self bit (because it’s wrapped inside the wrapper). And now we can tidy up recurWrapper a bit. Shortening parameter names a bit and naming the recur function (instead of assigning the anonymous function to a variable called recur) gives us this:

var recurWrapper = function(f) {
    function recur(forRec) {
        return function(n) {
            return f(forRec(forRec))(n);
        }
    };
    return recur(recur);
};

There is a better name for recurWrapper, and that is Y:

function Y(f) {
    function recur(r) {
        return function(n) {
            return f(r(r))(n);
        }
    };
    return recur(recur);
}

which is really the JavaScript version of the (applicative-order or not? we shall see) Y Combinator. And it works with any single argument anonymous function that is supposed to be recursive. For example, here’s Y with a function to compute the Fibonacci number:

var fibo = Y(function(f) {
    return function(n) {
        if(n <= 2) {
            return 1;
        } else {
            return f(n - 1) + f(n - 2);
        }
    }
});

Applicative Order Y Or Not (And What The Heck Is That?)?

Here’s a good explanation. In short, there are two ways of evaluation in programming languages. Applicative order is eager evaluation: arguments to a function are evaluated first before the function itself is executed. Whereas the normal order is lazy. Arguments to functions are evaluated when they need to be evaluated.

As such, there are two flavours of Y as well. The classic Y Combinator works when we’re using normal order of evaluation, but will hang when the evaluation is applicative order (just like in JavaScript, which evaluates the arguments first before a function is called). This normal Y Combinator is defined as such in lambda calculus:

Y = λf·(λx·f (x x)) (λx·f (x x))

which is closer to this:

function normalY(f) {
    function recur(x) {
        return f(x(x));
    }
    return recur(recur);
}

Which will hang, obviously, if you think in the applicative order way of thinking. The Y we just derived earlier, on the other hand, is applicative order. Note the difference in lambda calculus definition (the difference is in bold italic):

Z = λf. (λx. f (λy. x x y)) (λx. f (λy. x x y))

and its corresponding JavaScript version:

 

function applicativeOrderY(f) {
    function recur(x) {
        return function(y) {
            return f(x(x))(y);
        }
    };
    return recur(recur);
}

Right. Okay. So What’s In It For Me?

Yeah. That’s it. What’s in it for me beyond the “oh, neat” factor? Er. Frankly, I’m not sure. In the real world, if I need to write a recursive function, I will just give it a bloody name. Like alucard(). And doing Y combinator in your JavaScript codebase will probably piss off a web designer who has the misfortune of maintaining your code in the future.

I guess the main benefit of this whole exercise is that I feel good about understanding the Y combinator at last. It won’t make me a better programmer, at least in the short run, but heck. Having an iPod also doesn’t make your life any better other than making you feel good. So there.

UPDATE: I was surprised to see a big jump in my blog stat! Turned out that Matt Jaynes submitted this article to Y Combinator Startup News, and then linuxer submitted it to programming subreddit!

Christophe Grand and others in reddit and news.ycombinator pointed out that JavaScript has a built-in way of doing this using arguments.callee (see also Christophe’s comment below for a short example of how this is done). My intention was to derive the Y Combinator using a language with which a lot of people (including myself) are familiar (that is, JavaScript), instead of answering the question “how does one make an anonymous function call itself in JavaScript?”, but thanks anyway, guys!

Chris Rathman pointed out here that I’m still using a named function for my definition of Y(). Here’s my definition of Y again:

function Y(f) {
    function recur(r) {
        return function(n) {
            return f(r(r))(n);
        }
    };
    return recur(recur);
}

This definition is probably easier to understand because it uses JavaScript constructs that are familiar to most people, but like Chris said, we can go for the fully anonymous variant. Douglas Crockford also has a fully anonymous version in his The Little JavaScripter page, but let’s see how we can get to there from the definition we’ve seen in this article.First of all, remember that in JavaScript, we can define and call a function at one go like this:js> var y = function(x) { return x * x; }(2);
js> y
4.0

So with that in mind, we can replace the last line “return recur(recur);” with an anonymous function that wraps around it like this:

var Y = function(f) {
    return function(recur) {
        return recur(recur);
    }( /* we must pass something here */ );
};

And now what’s left, is to call this anonymous function directly, passing the (anonymized) body of the recur function in my original definition of Y. Like this:

var anonY = function(f) {
    return function(recur) { return recur(recur); } (
        function (r) {
            return function(n) {
                return f(r(r))(n);
            }
        }
    );
};

Which looks a little different from Douglas Crockford’s version (which is more similar to the one Chris posted in reddit), but they’re really different ways of saying the same thing. Man! This whole thing surely has been real educational for me :) (And I hope for you too!) Thanks very much, everyone!

Written by rayfd

May 6, 2007 at 5:37 am

Posted in Java, JavaScript, Technology