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
July 6th, 2007
I’ll be packing up and shipping off to Melbourne, Australia at the end of July to be a little closer to my Melbournian girlfriend. Exciting – if stressful – times ahead with the big move! I’m also looking forward to learning all I can from the top-notch Java developers at Shine Technologies when I start my new job there on the 6th of August.
I’ve started writing my Ocaml tutorial after tinkering further with the language over the past few days. I was hoping to have part 1 sorted out tonight, but it’s late and I’m exhausted. Sorry for the delay. It is coming. Honest.
Categories: Life |
5 Comments
July 4th, 2007
I stumbled across CodeIgniter for the first time today. It seems people have been using it for a while, but this is the first time I’ve been made aware of it. I had a chance to give it a run through the gauntlet on a recent project.
I have to say it’s actually pretty decent as far as PHP frameworks go. It’s unobtrusive without being half-assed. It’s powerful without feeling overwhelming. It just damn well works and doesn’t try to do more than it should.
This is high praise coming from me. Despite the six years of commercial PHP development behind me, I think PHP sucks. Further, I’ve rejected outright frameworks like CakePHP and Symfony, most of which feel like they were too busy wishing they were Rails and doing a little too much “magic”. Ruby makes the magic in Rails beautiful and manageable. In PHP, things feel far less elegant and the “Rails-esque” PHP frameworks often reflect that awkwardness. CodeIgniter avoids this pitfall by providing a solid foundation on which to build web applications and sites without getting the way.
It’s not all roses though. Like any other framework, CodeIgniter has its warts: The validation and pagination libraries are a little awkward to configure, the “Model” portion of the MVC framework feels relatively weak, it wouldn’t hurt to merge some libraries/helpers and add others with more utility. Inevitably you still suffer from PHP’s shortcomings: a flat namespace, shit OOP support (for PHP4, anyway) and the unpredictable naming conventions of the standard library. Not that this is CodeIgniter’s fault, just another failing of the PHP as a development language and platform.
On the whole, however, CodeIgniter gives a big bang for its buck and, given a few years, could prove to be a formidable framework indeed should Zend come up short. I highly recommend giving it a careful look and evaluating it for your next web project.
Categories: PHP |
No Comments
June 27th, 2007
GtkClipboard is a wonderful (if somewhat recent) addition to GTK. As you would expect, it allows users to pass data between your application and other GTK applications via the X11 clipboard (and vice versa). A common past annoyance with the clipboard under linux is that data stored disappeared from the clipboard when the application which set the data terminated. No longer so, thanks to gtk_clipboard_store and the GNOME Clipboard Daemon.
Now, tutorials on GtkClipboard are a little sparse and the documentation seems to leave a few questions unanswered, so here’s a quick and dirty primer on passing text data between your GTK applications using GtkClipboard.
Python
import pygtk
pygtk.require('2.0')
import gtk
# get the clipboard
clipboard = gtk.clipboard_get()
# set the clipboard text data
clipboard.set_text('Hello!')
# make our data available to other applications
clipboard.store()
Ruby
require 'gtk2'
# initialize Ruby's GTK bindings
Gtk.init
# get the clipboard
clipboard = Gtk::Clipboard.get(Gdk::Selection::CLIPBOARD)
# set the text. Ruby-Gnome2 also provides a text= setter
clipboard.set_text('Hello, World')
# make the clipboard data available to external applications
clipboard.store
C
#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <string.h>
int main (int argc, char **argv) {
const char *message = "Hello, World";
/* initialize GTK */
gtk_init (&argc, &argv);
/* set the clipboard text */
gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), message, strlen(message));
/* store the clipboard text */
gtk_clipboard_store(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD));
return 0;
}
You can also use gtk_clipboard_set_image (for Ruby and Python, there are equivalents) to pass GdkPixbuf data to the clipboard. Check the GTK/PyGTK/Ruby-Gnome2 documentation for more details.
It’s actually all quite easy, but I thought it might be nice to see the code in practice.
Categories: C, GTK, Linux, Python, Ruby, Software Development |
3 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
June 12th, 2007
Brushing up on my Java for the first time in a while and I came across something fairly trivial but new to me. If you’re a seasoned Javanaut, you’ll have to indulge me for a second
.
When writing a method within an anonymous/inner class in Java, the “this” keyword obviously refers to the anonymous/inner class itself. What if we needed a reference to the instance of the outer class?
public class OuterJFrame extends JFrame {
public OuterJFrame() {
super("Outer/Inner/Anonymous Classes Test");
JButton button = new JButton("Click me!");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
// type error! "this" refers to our ActionListener instance
chooser.showOpenDialog(this);
}
});
}
}
I stumbled across the answer to this little dilemma in the Java SE documentation: it is possible to refer to refer to the instance of the outer class using OuterClass.this:
public class OuterJFrame extends JFrame {
public OuterJFrame() {
super("Outer/Inner/Anonymous Classes Test");
JButton button = new JButton("Click me!");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
// fixed! this works as expected
chooser.showOpenDialog(OuterJFrame.this);
}
});
}
}
Obviously this neat little syntactic tango won’t work with static inner classes, because they are not associated with instances of the outer class. Still useful, yeah?
Categories: Java, Software Development |
No Comments
June 9th, 2007
I wanted to make a slight modification to the gaim source on one of my systems and found I was unable to build the application due to missing build tools and dependencies. Stumbled across this in an obscure thread in the Ubuntu forums:
$ apt-get source <package>
$ sudo apt-get build-dep <package>
$ (cd <package> && sudo dpkg-buildpackage -b -uc -d)
You’ll need to install build-essential for build-dep to work. If the stars are aligned, you should now have a ready-to-install .deb file. Install it using the following command:
dpkg -i <package>-<version>.deb
UPDATE 2009-04-21: fixed plurals and stuff … only took me about a year and a half to notice! Oh and thanks for your comment, Richard.
Categories: Linux |
1 Comment
August 2nd, 2006
NOTE: This is an old post which I am merely republishing. The earlier version was lost due to a RAID failure on my former web host’s server.
I had a bit of trouble tracking down decent documentation for Ruby/SDL and Ruby/OpenGL, so I thought I’d put together some sample code in case anybody is interested in it.
require 'sdl'
require 'opengl'
# initialize SDL and OpenGL
SDL.init(SDL::INIT_VIDEO | SDL::INIT_AUDIO | SDL::INIT_TIMER)
screen = SDL.set_video_mode(800, 600, 16, SDL::HWSURFACE | SDL::OPENGL)
GL.ClearColor(0.0, 0.0, 1.0)
GL.ClearDepth(1.0)
finished = false
while not finished
# pull events from the input queue
while event = SDL::Event2.poll
# watch for quit events
if event.kind_of?(SDL::Event2::Quit)
finished = true
break
end
end
# clear the screen
GL.Clear(GL::COLOR_BUFFER_BIT | GL::DEPTH_BUFFER_BIT)
# TODO: rendering code goes here!
# display the back buffer
SDL.GL_swap_buffers
end
# terminate SDL
SDL.quit
Obviously, the convention is underscored lower case method names for Ruby/SDL (although camelCase aliases are provided too), while Ruby/OpenGL’s API uses UpperCamelCase and breaks Ruby convention by using a capital letter for the first character.
Update: Here’s documentation for Ruby/SDL .
Categories: Graphics Programming, Ruby, Software Development |
No Comments