January 23rd, 2008
I’m still somewhat in holiday mode, so this entry is probably going to feel a little cheap for those of you following my more technical posts. I’m a big fan of GTK+ for user interfaces. If you don’t have the option or desire to use the Java platform and Swing, GTK+ is one of the better cross-platform user interface toolkits out there.
It’s high-level enough that it is easy to build quick, effective GUIs but low-level enough not to get in your way when you need to start messing around at the pixel level. GUIs can be built by hand using code, or designed using Glade and exported to an XML document to be loaded at runtime by any GTK+ binding. Currently it runs on Windows and Linux (the toolkit actually has its roots in GNOME) and has bindings for most popular programming languages. The only major downer is that Mac users are left out in the cold unless they go to the (herculean) effort of getting X11 up and running.
All the little differences between the various GTK+ bindings out there tend to get my goat when I move from one language to another. You would think that a GTK+ example in C could easily be translated to other languages without referencing documentation right? For one reason or another, the GTK+ bindings for other languages tend to diverge from the pleasant consistency of the C API to varying degrees. This post is all about those little differences that crop up even in the simplest applications: GTK’s take on “Hello World” in a few different languages.
C
C, being the language GTK+ is actually written in, is probably the most consistent with function naming across the different objects … the GTK_* and G_* macros are quite ugly though.
#include <gtk/gtk.h>
int main (int argc, char **argv) {
GtkWidget *window;
gtk_init(&argc, &argv);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Hello, World");
g_signal_connect (G_OBJECT (window), "delete-event", gtk_main_quit, NULL);
gtk_widget_show_all (window);
gtk_main();
return 0;
}
C#/Mono
GTK# adds stuff like the Application object and delegates to produce a “Hello World” example I had to go digging around in documentation for. Not too bad on the whole, though.
using Gtk;
using GtkSharp;
public class HelloWorld {
public static void Main(string[] args) {
Gtk.Window window = new Gtk.Window();
window.Title = "Hello, World";
window.DeleteEvent += delegate { Application.Quit(); };
window.ShowAll();
Application.Run();
}
}
Ocaml
The Ocaml bindings diverge from the original C API much more so than the other languages listed here, most likely due to design decisions that had to be made to provide a C binding to a functional language. My only real grumble is the inconsistency with window#event#connect vs window#connect. I’m guessing there was a technical reason for that, but it still irks me every time I see it.
let delete_event evt = false
let destroy () = GMain.Main.quit ()
let main () =
let window = GWindow.window in
let _ = window#set_title "Hello, World" in
let _ = window#event#connect#delete ~callback:delete_event in
let _ = window#connect#destroy ~callback:destroy in
let _ = window#show () in
GMain.Main.main ()
;;
let _ = main () ;;
Perl
Although I find writing Perl to be painful for everything but processing text files in a terminal, I found the Perl GTK bindings to be relatively straightforward.
use strict;
use Gtk2 '-init';
my $window = Gtk2::Window->new;
$window->set_title("Hello, World");
$window->signal_connect('delete-event', sub { Gtk2->main_quit; });
$window->show_all;
Gtk2->main;
Python
I’m more familiar with PyGTK than with other bindings, so this was a snap. Why they chose GtkObject.connect over GtkObject.signal_connect is a mystery and the pygtk.require(’…’) crap is a little weird, but aside from that there should be nothing surprising here (this is a good thing!).
import pygtk
pygtk.require('2.0')
import gtk
window = gtk.Window()
window.set_title('Hello, World')
window.connect('delete-event', gtk.main_quit)
window.show_all()
gtk.main()
Ruby
RubyGNOME provides a GTK+ binding for Ruby. Take an almost 1:1 port of the C API, take away the ugly casting macros, mix in closures for handling signals and Ruby really is one of the nicest ways to get intimate with GTK+.
require 'gtk2'
window = Gtk::Window.new
window.title = 'Hello, World'
window.signal_connect(:delete-event) { Gtk.main_quit }
window.show_all
Gtk.main
That’s all for now. There are many more language bindings for GTK+ out in the wild for languages like Lisp/Scheme, C++, Haskell and Erlang. If you’re looking around for a GUI toolkit, be sure to give GTK a go. There’s plenty of documentation available for all the bindings listed here, often with some very detailed and easy to follow tutorials.
UPDATE: Miguel and she suggested some changes to the C#/Mono and RubyGNOME examples.
UPDATE 2: Aristotle suggested an easier way to initialize the Perl GTK bindings.
Categories: C, GTK, Ocaml, Python, Ruby, Software Development |
11 Comments
October 3rd, 2007
Welcome to part two in my series of Ocaml tutorials! There was an overwhelming response to the first tutorial in the series and I have taken plenty of suggestions on board for this and future tutorials. In this instalment I’ll be introducing the list data type and the very useful List.iter function from the Ocaml standard library.
An Introduction to List Initialization and List.iter
Here’s the source code we’re going to be breaking down:
let main () =
let seq = ["a"; "b"; "c"] in
List.iter print_endline seq ;;
let _ = main ()
Looks scary, doesn’t it? It’s actually quite simple, but we’ll get to the source code in a moment. First, let’s see the program’s output. Save this file as tmhoo02.ml and run it like so:
$ ocaml tmhoo02.ml
You should see the following:
a
b
c
Now, let’s take a look at the interesting bits of the source code:
let seq = ["a"; "b"; "c"] in
As you (hopefully!) learned in part 1, the let syntax binds the variable seq to some expression. The in keyword indicates that this binding is a named local expression whose value to be discarded when the function exits (think “local variable”). But what exactly does that expression mean?
["a"; "b"; "c"]
This is the most direct way to initialize a list in Ocaml. Each element in a list is separated by a semi-colon. This particular list has three elements: the strings “a”, “b” and “c”. As our list comprises of string elements, we can say that this is a string list. Note that unlike some dynamically typed languages (e.g. Python and Ruby), every Ocaml list element must be of the same type: you have a list of string elements or a list of integer elements, but you simply can’t mix the two. Honestly, it won’t compile.
List.iter print_endline seq ;;
Here we’re calling the iter function of the List module – a module which is bundled as part of the Ocaml standard library. This function takes two parameters: the first is another function that accepts a single parameter, the second is a list.
As you might suspect, List.iter iterates over the list, passing each element in the list to the function one by one. To word it another way, inside List.iter we’re calling print_endline for each element in our list to the equivalent of: print_endline “a”, print_endline “b”, print_endline “c”. This explains the output of our example program.
Finally:
let _ = main ()
main is evaluated here and its return value (the <em>unit</em> value) is ignored by the underscore wildcard. You’ll notice in part 1 I omitted everything up to the equals operator but, at the behest of others who know better, I’ve included it here in part two. I’m not going to say anything more about it, other than the fact that the underscore wildcard is a simple but powerful construct you’ll likely become very familiar with at a later date. If you’d prefer to use the syntax from part 1, that should work too (but don’t come crawling to me when other Ocaml programmers come down on you like a ton of bricks
).
Advanced Discussion of the Type System
As a sneak preview into Ocaml’s type system, I can tell you that List.iter isn’t restricted to string lists. In fact, it can work with lists containing elements of any type. However, because each element of the list is passed to the function given to List.iter as the first parameter, that function must accept a parameter the same type as a single element in the list. Since print_endline accepts a string, we must use a string list. Or: since we’re passing in a string list as the second parameter to List.iter, the function passed as the first parameter must itself accept a string as its sole parameter.
Confused? Read that last paragraph again carefully. If you still don’t understand it, don’t worry too much: we’ll cover Ocaml’s type system more in the next few tutorials.
Until Next Time …
So that wraps up tutorial number two. I’ve already got parts three and four in the pipeline and I can tell you they introduce a fair bit of new material. Take your time trying to understand what was covered in this tutorial and post a comment or two if you have any suggestions, questions or improvements.
Categories: Functional Programming, Ocaml, Software Development, TMHOO |
No Comments
July 17th, 2007
Spent the afternoon cobbling together a simple Ocaml web server and – to spite my normally reclusive attitude when it comes to personal projects – I thought I’d share the results. The interesting stuff is in thumper.ml. Refer to line 215 if you’re interested in implementing your own handlers for primitive resources.
I’m sure there’s room for improvement, so I’ve uploaded a tarball of the bzr repository. You can get it here:Â Thumper v0.1. Any suggestions/patches?
Note: This is not the next part of my series of Ocaml tutorials. That’s likely to come after I’ve finished moving.
Categories: Functional Programming, Ocaml, Software Development |
3 Comments
July 6th, 2007
DRAFT: I’m still learning Ocaml myself, so some of what I say here may be plain wrong or misguided. I’m relying on those more experienced with Ocaml to correct my mistakes! If you have plenty of Ocaml experience, please correct my mistakes. By all means, be brutal!
Welcome to the very first part of my (hopefully enlightening) series of tutorials on the Ocaml programming language! In this tutorial we’ll be learning the Ocaml flavour of everybody’s favourite program: Hello World.
Since those interested in Ocaml will likely be coming from such a background, please note that this tutorial is written under the assumption that readers will have experience with other, imperative languages such as Java or C++. Now, on with the code:
let main () =
print_endline "Hello, World!" ;;
main () ;;
Save this file as tmhoo01.ml. You can run this program from the command-line using the following:
$ ocaml tmhoo01.ml
Or compile it to native code:
$ ocamlopt -o tmhoo01 tmhoo01.ml
Predictably, running this program displays “Hello, World!” in the console window. It’s not the output we’re interested in, however: it’s Ocaml’s weird ass syntax! Let’s take this line by line:
let main () =
This declares a function called “main”. let is an Ocaml keyword which defines named expressions (sometimes called let-bindings). In this case, the name of our expression/let-binding is “main”.
main takes a single parameter: the parentheses () represent what is known as the “unit value”. It is the only possible value for the unit type, and has a similar use and meaning to what void has in C/C++. In this case, it means the function main accepts no other parameters. This is necessary because Ocaml functions must always be applied to one or more parameters: thus, when we have no parameters to pass we must resort to using (). If we do not accept this unit parameter at a minimum, the expression in main is evaluated at the next double semi-colon ;;. This is not our intention.
print_endline "Hello, World!" ;;
The print_endline call does as you would expect. Similar to System.out.println or printf. print_endline returns the unit value. Implicitly, our main function has a unit type. This distinction may not completely make sense just yet, but the importance of this will make sense later once we start doing more work with different types.
The ;; keyword is used to separate multiple top-level constructs (e.g. let-bindings and class definitions). Later, you will use ; to separate expressions within other constructs.
main () ;;
As you would expect, this calls our main function.
So that’s our first Ocaml program dissected. Thanks for reading! If you have any questions or comments, please post them here: I’ll surely be revising this article based on your recommendations.
UPDATE 1: Correction to the descriptions of ; and ;;. Thanks Paul!
UPDATE 2: Removed my haughty claim that Ocaml references are more like C++ pointers than Java references. Cheers Chris!
UPDATE 3: Tried to otherwise simplify the tutorial. Less “blah blah blah”!
UPDATE 4: Remove introduction to references all together. Several people felt it was out of place to introduce a concept like references in the first tutorial. I happen to agree.
Categories: Ocaml, Software Development, TMHOO |
16 Comments
June 15th, 2007
My Introduction to Haskell
A few years ago when I was studying for my degree at university, I took a class on functional programming using the Haskell programming language. It was very instructional, if a little abrupt. I struggled with the language initially, despite being very comfortable with a number of other (imperative) languages. Once it started to click, however, I started to get a glimpse of the power must inevitably draw many toward the functional paradigm.
The project we were given was to build on an existing compiler (written in Haskell) for a simple, strictly-typed programming language devised by the lecturer. Once the lexer & parser had been extended with the new features, we also had to generate custom bytecode for the new features. Finally, we had to write an interpreter for the bytecode in C or Java. Compiler development was something I had always felt was out of my reach but the more I toyed with the code, the more comfortable I became with Haskell’s fairly alien syntax and – in turn – with extending the compiler itself.
The Joy of the Functional Paradigm
Within an hour or two, my extensions to the mini-language meant that I could now assign values to variables. Another few hours, and I had a for loop. Another, and I had enumerations and constants. The byte code generator, however, required me to step out of the mindset I had been in for half of the day: How do I now turn the AST generated by the parser into bytecode?
By this stage I was becoming comfortable enough with Haskell that I was able to work out the basics from the code used for the original language constructs. I was beginning to get a rough idea by the end of the first day and another day or two later, the project was finished. Thinking about it now, this was perhaps the only university unit that I really, really enjoyed. It was fun. Haskell and the constructs of the parser framework we were using were powerful tools. I had achieved something completely new and exciting using a language I was almost totally unfamiliar with.
The Return to Functional Languages: Ocaml
Fast forward maybe three years. I haven’t really touched Haskell since. Sure, I tried – but without a practical application for it there was no real drive. The passion I that had grown for compilers led me to the Python source code and, eventually, to PEP 341 where I was able to scratch a long-standing itch in the form of the try/except, try/finally statements. Due to the recent introduction of an AST, the changes were generally limited to the grammar and the AST and – although satisfying – were relatively trivial to implement.
As far as code contributions for Python go, I’m sure that I just need more practice and experience with the source. However, I still long to test the waters with functional languages again. Haskell, while it proved to be powerful and fun, lacks the supporting libraries to make useful (in the short term, anyway) only to academics and those willing to slog it out writing their own support code. Scheme was intriguing, but I’m still not sure which implementation I should be using nor did it have a useful library. Then I started hearing about Ocaml. A powerful functional programming language with support for imperative and/or object-oriented programming, Ocaml also sports a decent (if a little bare and disorganized) framework for all the basics.
A Lack of Tutorials
Documentation for Ocaml’s libraries exist, but tutorials for learning Ocaml properly are few and far between. http://www.ocaml-tutorial.org offers lots of information for those patient enough to read it, but I found it a little hard going.Further, there was little in the way of web, network/socket, graphics and UI programming.
The Big Tutorial Idea
I’m going to try and learn Ocaml myself using whatever resources I can find and hopefully distill the information and knowledge I come across in an easy-to-follow manner. Obviously I’ll be learning as I go, so the more jaded Ocaml and functional programmers should certainly point out the foolish errors of my ways.
Eventually I’d like to compile these posts into a proper tutorial for newcomers to Ocaml – although not necessarily newcomers to programming. From my limited experience with Ocaml, I can already see it’s a powerful language with much to offer. Keep an eye out for part 1 of TMHO later next week! Any suggestions/comments?
Categories: Compilers, Ocaml, Software Development, TMHOO |
5 Comments