The Blog

30 Aug 2004: Exceptional syntax and the need of a better parser

Suppose you want to collect the contents of some text files, but you want to tollerate any exceptions thrown in the File.OpenText method. Piece of cake, isn't it, you start XEmacs and type:

using System; class CollectFiles { public static Collect (file_names : list <string>) : string { | [] => "" | file_name :: rest => def file = try { File.OpenText (file_name) } catch { _ : Exception => null } if (file != null) { def s = f.ReadToEnd (); f.Close (); s + Collect (rest) } else Collect (rest) } }

But wait. Is this code ellegant? I don't think so, sir! Fortunately for us, some people came up with a better language construct to handle such situations:

| file_name :: rest => def f = File.OpenText (file_name) unless { _ : Exception => Collect (rest) } def s = f.ReadToEnd (); f.Close (); s + Collect (rest)

Much more readable, in my (Pawel's) opinion. Doesn't it look a little bit like Perl's `expr || die'? :)

It comes at a price though. The Nemerle parser can't handle such a construct on its own, we would have to clutter the parse tree with an additional node for the `unless' statement and expand it during typing -- and that's something I would like to avoid for a number of reasons. I guess this feature will have to wait until we develop the new parser supporting rewriting-based syntax extensions. I hope this will be the first thing we jump on after the 0.2 release.

Your comments are welcome!. Some of us (Michal :-), are not perfectly happy with the syntax above, your opinion does matter!