Sunday, February 20, 2011

Non-Trivial Union

In my last post I talked about placing some syntactic sugar around C++ unions. In that post I mentioned that having non-POD types - those with user-supplied or non-trivial constructors - were not allowed as a member of a union. In this post I describe how to overcome that limitation and why that might be useful.

First, to illustrate what I mean about unions not being allowed to contain non-POD types look at the following example:

struct Test {
    int i;
    Test () : i(0) {}
};

// ... and, later, in main
union NotAllowed {
    Test test;
    unsigned char bytes[sizeof(Test)];
};

Compiling that will present an error similar to

member ‘Test main()::NotAllowed::test’ with constructor not allowed in union

The workaround to this limitation is to store a pointer to the type and manage the memory external to the union. Well, it would be really nice to support RAII with unions since they actually support the constructor and destructor mechanism but the storing-a-pointer-to-type approach defeats this. I wanted to see if there was any way to use RAII with C++ unions.

I started out by considering using the union constructor to do a memcpy on the size of the complex type to itself but the obvious failure there is that the constructor/destructor of the type is still managed outside the scope of the union. In addition to that, memcpy would provide only a copy of the memory of the object so I could not manipulate the object itself.

After a little reading I found out about a cool mechanism called placement new operator. What placement new will do is allow you to provide a memory location to store an object and use that instead of what operator new would normally provide for you. The best part about that is that the constructor of the object is invoked. I looked around a bit and from what I saw placement new is generally used to provide memory pools or other memory management mechanisms outside of the default behavior of new and delete. So, continuing with my example from last time, I derived the following

#include <stdexcept>

template< typename T >
union NonTrivialUnion {
    private:
        T * ptr_;
        unsigned char bytes_[sizeof(T*) + sizeof(T)];
    public:

        NonTrivialUnion (const T& t) {
            ptr_ = new (bytes_ + sizeof(T*)) T(t);
        }

        NonTrivialUnion () {
            ptr_ = new (bytes_ + sizeof(T*)) T;
        }

        ~NonTrivialUnion () { ptr_->T::~T(); }

        T * operator-> () { return ptr_; }

        // ... remainder of implementation 
        // ... operator[], operator=, ...
};

The placement new is in the union constructor

ptr_ = new (bytes_ + sizeof(T*)) T(t);

You'll also notice in the destructor of the union that I explicitly call the destructor of the object I am maintaining. This is necessary. As I mentioned, the storage location is not provided by new so delete would do undefined things with it and as delete is responsible for calling an object's destructor it follows that the destructor needs to be called elsewhere. Hence, in the destructor of the union there is

~NonTrivialUnion () { ptr_->T::~T(); }

I'm also being sneaky by extending the size of the union by the size of a pointer so I have some way to access the memory as you would with a pointer to an object. This does break the strict rule of what a union is: the size is no longer exactly that of the object. However, with that caveat, we can now do the following:

#include <iostream>
#include "ntu.hh"

struct Test {
    int i;
    Test () : i(0) {}
    void echo(const char * msg) { std::cout << msg << std::endl; }
};

int main () {
    NonTrivialUnion< Test > ntu;
    ntu->echo ("Allowed!");
    return 0;
}

Notice that I am not just storing a copy of the memory of an object as I would be with memcpy; that memory is the object itself entirely managed by the union. Constructors and destructors are properly called and you can call through to the object to invoke it's member functions. Pretty cool.

One note about the above example: it relies on an empty constructor for the object. There is support for a non-empty constructor using the following approach

Test t;
NonTrivialUnion< Test > ntu(t);

But in that case a copy-constructor is used and exactly two objects are created: one external to the union and one owned by the union.

There needs to be much more thought about how to implement the union robustly. For example, operator= for unions supporting more than a single type; and how to dynamically determine the largest type among multiple members; and so on. Regardless, I think this is an interesting and useful tool.

Thursday, February 17, 2011

C++ unions

I was reading Bruce Eckel's Thinking in C++ the other day and I came across a bit of information that I was not aware of: unions can be treated just like classes. That is, they can have constructors and member functions and access control.

I think that this is a neat feature. Combined with the use of templates and operator overloading one can create a shared memory space (just like you normally would with unions) but with a much nicer interface. Consider the following:

#include <stdexcept>
#include <sstream>

template< typename T >
union Bytes {
    private:
        T data_;
        unsigned char bytes_[sizeof(T)];
    public:

        Bytes(const T& t) : data_(t) {}

        T& value () { return data_; }

        size_t size () const { return sizeof(T); }

        void operator= (const T& t) { data_ = t; }

        unsigned char& operator[] (int i) {
            if (i < 0 || i >= size()) {
                std::stringstream ss;
                ss << "Invalid index " << i << " ";
                ss << "(sizeof(T) : " << sizeof(T) << ")";
                throw std::out_of_range (ss.str ());
            }
            return bytes_[i];
        }
};

Now you can have a shared memory space that can be accessed with operator[] for the individual bytes of any POD type (unions do not support objects with constructors) and operator= for setting the value of the type.

The result is mostly syntatic sugar but makes for much more readable code:

Bytes<long> memory(0);  // initial value of 0
memory[1] = 4;          // modify individual bytes. New value 1024
memory = 0;             // reset value to 0

Saturday, February 5, 2011

Goto Hell

There was a recent stackoverflow challenge question where users were asked to present code that prints the numbers 1 through 1000 without using loops or conditionals. A major theme for answers to the thread was recursion - both compile time and run time. There were a mix of other entries including consecutive function calls to iterate through 1000 increment/print operations, shelling-out to a program such as seq, and several other approaches to the problem. My first opinion was that the only correct solution (according to the spec) was the one that used constructors. I say correct because, technically, recursion is looping.

I posted my own solution for fun which aimed to solve the problem in a way not currently presented. This is both an abuse of compiler extensions and language constructs and is nothing more than me having some fun. Really, don't write code like this. Ever.

#include <stdio.h>

int main () {
    void * label[1001] = { [0 ... 999] = &&again };
    label[1000] = &&done;
    int i = 0;
again:
    printf ("%d\n", i + 1);
    goto *label[++i];
done:
    return 0;
}

I knew that if I considered recursion a loop that my code was also a loop construct. The point of my post, however, was to have a solution that was entirely distinct from what had already been posted and not necessarily to solve the puzzle exactly. This got me thinking though; how close is state machine looping, and recursion, and compile-time recursion to an actual coded loop?

I coded up and compiled three implementations with the intent of determining what the code looked like after the compiler was finished with it. The solutions I chose were: compile time recursion, run time recursion, and my goto looping. Each of these was compared to a basic for loop. Because of template stack depth issues I've only printed up to 10 in these examples. All files were compiled by g++ -O0 (except my solution, see below). In all assembly output the comments are my own.

Compile Time Template Recursion

template< int N > void fun () {
    fun< N-1 >();
    std::cout << N << '\n';
}

As asm

...

_Z3funILi1EEvv:                 ; fun< 1 >
    pushq   %rbp
    movq    %rsp, %rbp
    movl    $1, %esi
    movl    $_ZSt4cout, %edi
    call    _ZNSolsEi
    movq    %rax, %rdi
    movl    $10, %esi
    call    _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_c
    leave
    ret
...

_Z3funILi2EEvv:                 ; fun< 2 >
    pushq   %rbp
    movq    %rsp, %rbp
    call    _Z3funILi1EEvv      ; fun< 1 >()
...

_Z3funILi3EEvv:                 ; fun< 3 >
    pushq   %rbp
    movq    %rsp, %rbp
    call    _Z3funILi2EEvv      ; fun< 2 >()
...

main:
    pushq   %rbp
    movq    %rsp, %rbp
    call    _Z3funILi10EEvv     ; fun< 10 >()
    movl    $0, %eax
    leave
    ret

This was a big surprise to me. I assumed that since the compiler was dealing with constant values and there was no class involved that this would actually be generated as a recursive expression. Instead, as you can see, the compiler actually generates all 10 function calls and arranges them to call each other in order where main calls _Z3funILi10EEvv which calls _Z3funILi9EEvv which, in turn, calls _Z3funILi8EEvv and so on - each printing a value after invoking the next function. The process bottoms out at _Z3funILi1EEvv where no function is called and only a value is printed. So this is essentially the same as creating a function for each value to be printed and calling them in order with the exception that the calls are actually nested instead of sequential. This is not recursion.

Run Time Recursion

void fun(int n) {
    n && (fun (n-1), std::cout << n << '\n');
}

As asm

_Z3funi:
    pushq   %rbp
    movq    %rsp, %rbp
    subq    $16, %rsp
    movl    %edi, -4(%rbp)
    cmpl    $0, -4(%rbp)    ; hidden conditional ;)
    je  .L9
    movl    -4(%rbp), %eax
    leal    -1(%rax), %edi
    call    _Z3funi         ; the recursion
    movl    -4(%rbp), %esi
    movl    $_ZSt4cout, %edi

    ; print setup stuff here

.L9:
    leave
    ret
...

main:
    pushq   %rbp
    movq    %rsp, %rbp
    movl    $10, %edi
    call    _Z3funi         ; start recursive call
    movl    $0, %eax
    leave
    ret

It is interesting to note that there is a hidden conditional in there. It applies to the short-circuit operation used to terminate the recursion. Other than that, there is nothing unexpected here. The only thing that might have changed this up a bit is if we could have done tail recursion; the compiler might have turned it into a loop. Requiring the print call to be the final executed statement of the function spoils any chance of that.

Goto State Table
 As a side note, I was not able to compile my submission as C++ code. In order to make the comparisons I've just used gcc instead - I don't imagine the result would be any different had g++ been willing to accept the code.

main:
    pushq   %rbp
    movq    %rsp, %rbp
    subq    $8048, %rsp
    leaq    -8016(%rbp), %rax
    movq    %rax, -8024(%rbp)
    movq    $0, -8032(%rbp)
    movl    $8008, %eax
    cmpl    $8, %eax        ; part of initialization, not my code
    jb  .L2
    movq    $1001, -8040(%rbp)
    movq    -8024(%rbp), %rdi
    movq    -8040(%rbp), %rcx
    movq    -8032(%rbp), %rax
    rep stosq
.L2:
    movq    $.L3, -8016(%rbp) ; again label

    ; lots of lines initializing jump table

    movq    $.L3, -24(%rbp)   ; again label
    movq    $.L4, -16(%rbp)   ; end lable
    movl    $0, -4(%rbp)
.L3:
    movl    -4(%rbp), %eax
    leal    1(%rax), %esi
    movl    $.LC0, %edi
    movl    $0, %eax
    call    printf
    addl    $1, -4(%rbp)
    movl    -4(%rbp), %eax
    cltq
    movq    -8016(%rbp,%rax,8), %rax
    jmp *%rax       ; non-conditional jump
.L4:
    movl    $0, %eax
    leave
    ret

And, for completeness, the for loop

main:
    pushq   %rbp
    movq    %rsp, %rbp
    subq    $16, %rsp
    movl    $1, -4(%rbp)
    jmp .L7
.L8:
    movl    -4(%rbp), %esi
    movl    $_ZSt4cout, %edi
    call    _ZNSolsEi
    movq    %rax, %rdi
    movl    $10, %esi
    call    _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_c
    addl    $1, -4(%rbp)
.L7:
    cmpl    $1000, -4(%rbp)     ; conditional
    jle .L8
    movl    $0, %eax
    leave
    ret

The really surprising thing to me was the result of C++ template recursion and that the generated code is not recursive. So, in addition to the constructor submission it seems that compile time recursion satisfies both requirements of the problem: no conditionals and no looping.

 As expected, there were conditionals in the resulting assembly for the run time recursion - they are necessary to ensure an exit condition. This is where I believe that I have a leg up on the recursive solutions: the goto approach does not rely on a condition to terminate. In both the run time recursion and straight for loop implementation the resulting [assembly] code boiled down to basically a check for continuation (the conditional) and a jump to a previous location (the loop). Neither are present in the template recursion or the constructor solution. My code sits somewhere in between. Though, I likely lose major points for style.

Saturday, January 29, 2011

Unbalanced Expression

For the most part, interviews have always gone easy for me which is curious because I have an almost uncontrollable fear of social settings. I'm generally so consumed by the anticipation of the event that when the meeting eventually takes place my technical reflexes take over. This is both a blessing and a curse: technical questions and topics are not a problem when in this state but a vague question about personality and past experiences tends toward meaningless rambling about nonsense. Social prowess notwithstanding I've come out on top more times than not in these adventures... until recently.

I interviewed at a startup company where there were two technical questions that I had trouble with. Incidentally, the 'who we are' and 'who are you' portions actually went much better than usual - I do love irony. In either case, the first question was related to querying billions of bytes of data to provide quasi real-time behavior to users. The question was intentionally vague leaving much open to interpretation and I pared it down as much as my experience supported: what is unique in the data, what are the time constraints, what about false negatives/positives, caching, backend structure, and so on. In the end I just came to the conclusion that I could not provide the design details that they were looking for and said so. This took about fifteen minutes and they did not seem too discouraged with my ultimate conclusion.

The second question was direct and significantly less open-ended - this is the part that really threw me for a loop. The question was this: 'Solve the following expression using any language you want'.

(((1+3)*7)+((((3-1)/(1+3))*8)))

Me: "Use eval in ruby or python"
Them: "Good. You can't use eval"
Me: "I'm not too familiar, but a Lisp interpreter?"
Them: ... confused, unexpected looks ...
Me: "Nah, that is incorrect Lisp format, never mind"
Them: "Yeah, that's not exactly proper Lisp format. What else?"

I asked if the expression would always be balanced and that we only had to deal with binary operators. The answer was yes on both counts so I started drawing stacks on the whiteboard roughing out what would work. Eventually, I presented the following Ruby solution:

$ops = []
$vars = []

OPS = ['(', ')', '+', '-', '/', '*']

def push_op op
    $ops.push op
    if op == ')'
        $ops.pop
        v2 = $vars.pop
        v1 = $vars.pop
        op = $ops.pop
        v = eval("#{v1} #{op} #{v2}")
        $vars.push v
        $ops.pop
    end
end 

def push_var v
    $vars.push v
end

$stdin.gets.chomp.split(//).each do |c|
    if OPS.include? c
        push_op c
    else 
        push_var c
    end
end
 
puts $vars.pop

(the eval part was agreed to be hand-waving for a more complex case statement)

The immediate reply was: "Nope. You've missed a fundamental flaw for this class of equations". So I went back and did the entire equation by hand and realized that the solution would not support the unary operation of (). That is, something like ((1+2)) would end up with my solution popping from an empty stack. So, I injected the fix and claimed that the problem was solved for balanced and valid equations. Here is the fix.

def push_op op
    $ops.push op
    if op == ')'
        $ops.pop
        if $ops[-1] == '('
            $ops.pop
            return
        end
        v2 = $vars.pop
        v1 = $vars.pop

Again, the reply was that I was missing the real fundamental problem with this type of equation. I asked if this particular solution exhibited the flaw they were talking about and they claimed it did. I was stuck at that point and ultimately left the interview with the sense that I failed some basic understanding of mathematical equations. When I got home, I typed up my solution and ran the input they provided and the output was exactly as I had expected (the same as an eval call). I wrote my follow-up email to the company thanking them for the interview but I also attached my script with sample run indicating that I stood by my solution from that afternoon.

What do you think... did I missing something obvious or were they looking for my ability to stand my ground when I had the best solution? They never conceded that I actually had the correct answer; in fact, they indicated that I should take it home and consider what I was missing.

So, yeah. I'm still a bit off-balance from that experience.

Saturday, January 22, 2011

C++ namespace

 
 
using namespace std;

It appears in almost every tutorial for beginners and the vast majority of books dedicated to C++. I suppose it saves more time than the alternative of teaching the proper mechanics to newcomers. For the most part, I suspect that you may never have a problem using the standard namespace in it's entirety. I think it's unfortunate, however, that this approach hides both the intent of namespaces and the pitfalls associated with not understanding their mechanics.

A namespace is a clarification tool: it announces the intended scope of the token it proceeds. If you have two tokens with the same name, placing them in separate namespaces prevents compilation errors due to name clashes. There are other functions of namespaces, such as clarity of code, but these are considered secondary if at all.

I've heard - and argued against - people who claim that using an entire namespace is perfectly fine and any claims to the contrary are bunk. To be clear; understanding namespaces is not as important as understanding pointers, references and proper use of classes. But, there are things to watch out for especially as a beginner. Most notably: masking and ambiguity.

Masking
The problem here is that including an entire namespace can mask errors in your own code. This example is something that is very common in those starting out in C++, particularly if they are coming from a scripted language background.

#include <iostream>
#include <algorithm>

using namespace std;

int main () {
    int x = 5, y = 3;
    cout << "Before swap: " << x << " " << y << endl;
    swap (x, y);
    cout << "After  swap: " << x << " " << y << endl;
    return 0;
}

void swap (int x, int y) {
    int tmp = x;
    x = y;
    y = tmp;
}

The intention is obviously to swap the values of two numbers. As it is written however, this swap will only modify the local variables leaving the original two unchanged. The problem lies in the fact that there is a std::swap defined that does the appropriate thing and we get:

Before swap: 5 3
After  swap: 3 5

Which is correct but masks two things that a beginner now won't notice: 1) the local swap is not recognized by the compiler before the use in main (no prototype) and 2) the std::swap version is being invoked and masking incorrect behavior.

If, instead of the entire namespace, we only used specifically the elements local to our scope we would resolve these issues. Changing 

using namespace std;
to 
using std::cout;
using std::endl;

would result in a compilation error similar to:

mask.cc: In function ‘int main()’:
mask.cc:10: error: ‘swap’ was not declared in this scope

Ambiguity
This is a problem of name clashing: two equally qualified matches to a function are present and the compiler can not discern which is to be used. There is a similar problem when two names clash and scope can be used in determining which function gets used. This is an even more subtle bug since there are no complaints from the compiler your code just uses the function with the innermost scope regardless of your intentions.

Consider:

namespace foo { void fun() { } }
namespace bar { void fun() { } }

using namespace foo;
using namespace bar;

int main () {
    fun();
    return 0;
}

Trying to compile that results in

ambig.cc: In function ‘int main()’:
ambig.cc:8: error: call of overloaded ‘fun()’ is ambiguous
ambig.cc:2: note: candidates are: void bar::fun()
ambig.cc:1: note:                 void foo::fun()

That is a painfully obvious example but working with much larger projects where multiple teams are committing code this becomes a real problem. Again, using only the relevant portions of a namespace or being specific when calling the function (bar::fun(), for example) solves this problem.



Another benefit of understanding how to use namespaces is cleaner code in some settings. Consider some of the code you may have seen for multi-platform projects:

void fun () {
#ifdef PLATFORM1
std::cout << "platform1::fun()" << std::endl;
#else
std::cout << "platform2::fun()" << std::endl;
#endif
}

with the logic of the platform sprinkled within the function bodies themselves. This is hard to read and even harder to maintain. With namespaces this can be cleaned up to separate each function body (one for each platform) into it's own namespace.

#include <iostream>

namespace platform1 {
    void fun () {
        std::cout << "platform1::fun()" << std::endl;
    }
}

namespace platform2 {
    void fun () {
        std::cout << "platform2::fun()" << std::endl;}
}

Now, the only place that needs platform logic is when we decide to use the namespace.

#include "platform.hh"

#ifdef PLATFORM1
namespace platform = platform1;
#else
namespace platform = platform2;
#endif

int main () {
    platform::fun ();
    return 0;
}

I can't remember ever seeing this approach suggested instead of the less robust macro everywhere code.



Again, with all errors you can run across in a C++ program the ones listed above are some of the easier to pinpoint. Beginners will have the most difficulty as they are not only struggling with a new language and syntax but with subtle errors that are masking behavior they don't even realize is incorrect. I don't think that teaching the proper use of namespace adds that much complexity to learning C++; it really is unfortunate that the topic is not done justice in most reference material.

Friday, January 14, 2011

Closures (Ruby v Python)

I'm a Ruby guy. I'm not religious about it, but when it comes to scripting, prototyping, parsing, or automation my instinct (read: comfort zone) is Ruby.

I've been working on a project lately where the dominant language is Python. This has required me to both learn a new language and break habits built in other environments. I like learning new things and I think that having your comfort zone invaded every once in a while keeps you on your toes so this experience hasn't been too painful so far. It's interesting, though, to evaluate what I consider habits against what I think are more along the lines of principles.

One thing that prompted this was the way Ruby and Python differ in handling closures. I could claim that this started back when I was a TA and had to grade dozens of projects written in Python over many disparate editors (tabs vs. spaces, anyone?) but I digress. In this case, I was using what was basically a callback and I really like they way Python handles this syntactically. Consider the following:


def foo():
    print("in foo")

fun = foo   # fun is now a function object
fun()       # this invokes foo()

Which is not possible (at least with a similar syntax) in Ruby. In Ruby what you get is

def foo
    puts "in foo"
end

fun = foo   # invokes foo because foo takes no arguments
            # would be an error if foo expected arguments

And since foo gets the return value of puts (nil) if you try to use it later in your code you get an error. You'd either have to use a lambda or Proc to get around the fact that the method is invoked. In Ruby, you can elide the parentheses when calling a method which makes the above behavior perfectly rational.

Advantage Python. Let's try and use closures to do something...

There is a cool feature in Ruby that I've found useful in the past in that I can create a function generator similar to the following:

def foo_gen
    x = 0
    return lambda { x += 1 }
end

Where the returned function would represent the list of integers starting at 1 and increasing each time the function is invoked. Something like:

foo = foo_gen
3.times { puts foo.call }

Which would print out the numbers 1, 2, 3. In fact, each new call to foo_gen creates a new infinite sequence starting at 1. In Python, this turned out to not be so easy. There is a subtle difference in how the lexical scope is represented when defining a Python closure. Consider what I thought was an equivalent Python construct:

def foo_gen():
    x = 0
    def foo():
        x += 1  # Error: x not in scope here
        return x
    return foo

Unfortunately, the variable local to the scope that the closure was defined in is not visible from the closure itself. This subtlety is actually related to why a Python class method definition requires an explicit this argument when it is defined and Ruby class methods do not. In either case, the workaround to this problem is something similar to:

def foo_gen():
    x = 42
    def foo(x=x):
        while 1:
            x += 1
            yield x
    return foo

Two things are important in the above change:

  • I am required to provide an argument to the function that receives the value of the locally (to the defining scope) bound variable. (The alternative is to define x as an array and increment the first index of that array - I don't fully understand why that is valid, however)
  • I am now using a generator and yielding the values explicitly requiring an infinite loop to enable the generator

I should note that, in Ruby, the yield still happens it's just hidden behind the syntax and without the need for an explicit loop construct.

I'm a fan of list comprehensions and functionality such as enumerate. Other features of Python are certainly growing on me quickly (though, ' '.join(lst) is still counter intuitive compared to lst.join ' '). And, while I can accept the white space requirement, the necessary parenthesis for function calls, explicit self argument in class methods and some of Python's other assembly as uncomfortable, I find this to be more or less broken.

I'm not intending to bash Python or praise Ruby. I've got miles to go before I am a Python master (or Ruby master, for that matter) and I am entirely open to the fact that in my journey I may come to understand this behavior. Until that point, however, I still feel icky writing code like that.

Wednesday, December 22, 2010

Small projects

There was a post recently in one of the forums I frequent about a new developer wanting to know what to do for a project. This is hardly a new question; the net is littered with remnants of first year CS students enamored with their new found abilities looking for ways to expand. In general, I suggest that a good way to build skills is to get involved with an existing open source program. The road map I layout is along the lines of:
  • Pick something that interests you
  • Start small (read and document some code)
  • Tackle increasingly difficult bug tickets
  • Develop portions (or all) of a small feature request
  • Rinse and Repeat
I'll also occasionally mention that an alternative is to pick something that you do not like about your everyday computer experience and make that better somehow. It is this last point that I'd like to expand on here. Not that the suggestion is altogether vague, but an example always helps to illuminate a point.

In my reply to the post mentioned above I made the comment that I own a MacBook and that one of the features that I really liked about it was the dashboard dictionary/thesaurus widget. In case you are not familiar, the widget allows you to enter a word and get what is basically a dictionary listing for that word. This is directly available from the desktop environment by way of the dashboard.

I also mentioned that I frequently do work in a Linux environment and that I miss the availability of this type of tool there. My experience to define a word in Linux is to load up a browser and search for the definition on the web. I explained that this is the type of thing that you could use as a starting point for a project to hone your skills. In my case, I decided to write my own little command-line tool that would define a word for me. This is a far cry from a translucent, fly-in, dashboard widget but it gives me the immediate satisfaction that I'm looking for on my Linux machine. For example:

ezpz@sandbox:define > define "Ignoratio elenchi"
 the logical fallacy of supposing that an argument proving an irrelevant point
 has proved the point at issue

 Ignoratio elenchi (also known as irrelevant conclusion or irrelevant thesis)
 is the informal fallacy of presenting an argument that may in itself be
 valid, but does not address the issue in question. ...

The result, I claimed, was that I got added goodness in my Linux environment and learned a few things along the way. In fact, I found that not adding 'Connection: close' to an HTTP request can have differing effects depending on whether or not you sit behind a proxy.

It's important when you are starting out to set meaningful, attainable goals - even if they are redundant (i.e. another tool does something very similar). The meaningful means that you get something tangible (or at least relevant) out of the experience but the attainable ensures that you do not bury yourself in something you can not hope to achieve.

Sure, there exist tools that do what my little command-line tool does. Yes, they are way more sophisticated. That misses the point. I worked to better my experience, learned something along the way and now I'm a better developer because of it. And as for taking my own advise on the rinse and repeat - I've recently purchased a machine with Windows 7 installed and there is no dictionary gadget included by default. Looks like I'm gonna be learning some Javascript to build me a new gadget.