Tuesday, 22 December 2009

The Joy of Haskell

About a year ago, I spent the best part of a day playing with Haskell, which was long enough to intrigue me as to its possibilities but not long enough to develop any real understanding of the language. Since then, my functional programming urges have lain dormant - until last week, when I decided to dust off my copy of Real World Haskell and spend a bit longer with the language.

So far, it has been an enjoyable experience, albeit a demanding one at times. I'm very impressed by the elegance and expressive power of Haskell. I've just been reading about currying and function composition and can sense a broadening of my mental horizons somewhat akin to that which I felt on first encountering the UNIX tools philosophy. It was a revelation then to realise just how much more flexible UNIX could be than rival operating systems, thanks to the idea of having many small, simple utilities, controlled via command line flags and connected via pipes. I'm beginning to feel that Haskell offers analogous benefits, compared with the other languages that I've been using for so many years.

That said, I'm encountering the odd thing that makes me cringe. A few of the functions seem to have rather ugly names - putStrLn being a prime example. But I guess I can learn to live with that.

Real World Haskell seems to be pretty good. My only significant quibble so far concerns the exercises, which could do a better job of reinforcing and building on the concepts introduced in the text.

It's too early to say whether my programming habits will be irrevocably changed by all this; I suppose it depends to a large extent on how much more time I'm prepared to spend on Haskell. I sense I'm on the verge of 'getting it', so who knows?...

Sunday, 20 December 2009

Appropriate complexity in Java and Python

I've blogged previously that the notion of appropriate complexity is important in determining how easy it will be to learn a programming language. Ideally, small, simple problems should be solvable with small, simple programs, and program size or complexity should not need to increase substantially if there is a small increase in the size or complexity of the problem - always assuming, of course, that we remain within the 'comfort zone' of the language.

Let's consider how well Java meets this requirement by looking at the traditional first program: one that prints "Hello, World!" on the console. If we were dogmatic about exploiting Java's object-oriented nature, then such a program would have to look something like this:
public class Greeting
{
  public void display()
  {
    System.out.println("Hello, World!");
  }

  public static void main(String[] args)
  {
    greeting = new Greeting();
    greeting.display();
  }
}
A complete novice who is already nervous about the challenge of learning programming will probably regard this code with dismay and wonder just how much more difficult writing a non-trivial program is likely to be.

One way of minimising the complexity is to develop and execute code within an environment that hides much of the 'scaffolding' - BlueJ, for example. Alternatively, we could simplify things by adopting a largely procedural style:
public class Greeting
{
  public static void main(String[] args)
  {
    System.out.println("Hello, World!");
  }
}
But even this simpler code is replete with potentially confusing details. The novice will no doubt be able to identify the single line of code that causes a message to be printed on the console, but will wonder
  • Why the line appears inside something called main
  • What purpose is served by String[] args
  • What the words public, static and void signify
  • What a class is, and why the code has to be enclosed within it
How does one deal with such questions? Is it better to explain every detail of the program, running the risk of confusing or intimidating the less experienced, less confident students? Or is it better to defer explanations until later, running the risk that students will not be confident about writing their first few programs because they don't understand everything that they are expected to type? Both approaches clearly have drawbacks.

Python suffers from no such problems, offering us what is surely the simplest version possible of the traditional first program:
print 'Hello, World!'
(The Python 3 version includes parentheses, of course, because print is a built-in function rather than a statement in Python 3.)

Saturday, 19 December 2009

Paul Cusick

Got an early present in the post the other day: Paul Cusick's Focal Point CD. A nice touch was the handwritten postcard from Paul himself, wishing me a Happy Christmas!

I discovered Paul via last.fm and recommend that you check out his work if you are a fan of contemporary rock music - particularly if you like the 'modern prog rock' sound of bands such as Porcupine Tree or The Pineapple Thief.

<a href="http://music.paulcusick.co.uk/album/focal-point-album">Focal Point by Paul Cusick</a>

Minimal surprise in Java and Python

I've blogged previously about the idea that a programming language will be easier to learn if it causes minimal surprise to the learner. Let's consider a couple of examples here.

Integer Division


In common with other popular languages like C, C++, Java, C# and Ruby, Python 2 implements 'floor division' for integers - so evaluating 1/2 will yield 0, for example. This is an unwelcome surprise for most programming novices, who naturally expect a language to implement the normal rules of arithmetic. In our experience of teaching Python 2 (and before that, Java and C++), most students make mistakes with integer division more than once before they learn to cope with this counterintuitive behaviour.

Python 3 changes int division so that it now returns a float value. The // operator can be used to obtain the old behaviour:
>>> 1 / 2
0.5
>>> 1 // 2
0
For some programmers whose expectations have been shaped by exposure to the C family of languages, this change has been the source of much anguish ever since it was first proposed in PEP 238 back in 2001 (as can be seen in comp.lang.python newsgroup discussion on the topic), but it removes what was clearly a significant hurdle for those new to programming.

Console I/O


In another post, I described the asymmetry in console I/O that exists in Python 2 as an example of redundancy, but it can also be viewed as an unexpected surprise. And there's something else, about console input specifically, that can be surprising to Python newbies.

For a long time, Python has had two built-in functions that read from the console: input and raw_input.

The first of these reads a string of characters and attempts to evaluate them, such that a sequence of digits yields an integer value, characters enclosed in quotes yield a string, etc. Unfortunately, this is less useful than it sounds. Consider the following simple Python 2 program:
# hello.py - a program that greets you

name = input('Who are you? ')
print 'Hello', name
Here are two attempts to run this program:
$ python hello.py
Enter your name: nick
Traceback (most recent call last):
  File "hello.py", line 3, in <module>
    name = input('Who are you? ')
  File "<string>", line 1, in <module>
NameError: name 'nick' is not defined

$ python hello.py
Enter your name: max
Hello <built-in function max>
In both cases, the student running the program has forgotten that string input should be enclosed in quotes, with the result that Python treats the inputs as names of objects in the global namespace. The first attempt fails because there is no object named nick, but the second attempt succeeds because Python has a built-in function named max. Both results are surprising, even baffling, to programming novices.

The less surprising option in Python 2 is to use raw_input instead of input. The raw_input function returns console input as a string object and allows the programmer to decide exactly how this string should be handled. The string can be left alone in cases where text is expected (as in hello.py) or it can be converted explicitly to the required type:
number = float(raw_input('Enter a value: '))
We have seen many cases where students have used input in their Python 2 programs, having failed to recognise that raw_input is a safer, less confusing alternative (in spite of our attempts to explain this most carefully). Python 3 prevents such confusion by providing a single function named input, equivalent to the raw_input function of earlier versions. Evaluation of the input string is still possible, but it must be done explicitly, with code like eval(input()).