Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
Ocaml compiler features
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2007-01-16 (02:12)
From: Jon Harrop <jon@f...>
Subject: Re: [Caml-list] Ocaml compiler features
On Tuesday 16 January 2007 01:18, skaller wrote:
> On Mon, 2007-01-15 at 23:17 +0100, Vincent Hanquez wrote:
> > On Mon, Jan 15, 2007 at 12:23:32PM -0800, Martin Jambon wrote:
> > > OCaml is well-enough designed so that there is no "common" syntax
> > > extension.
> >
> > There ARE common syntax extensions.
> > how many people miss a try-except-finally construct ?
> > how many people miss a return statement to break the flow of a function.
> > etc ..
> I don't miss any of those things .. the point being they're
> not so 'common' as you might think.

try ... finally is useful when closing file handles.

However, simply trying to read a file as a list of strings is a sticking point 
for many newbies because the obvious functional implementations aren't 

  let rec read ch = try input_line ch :: read ch with End_of_file -> []

Elegant but not tail recursive. Conventional transformation into tail 
recursive form using an accumulator:

  let rec read ?(t=[]) ch =
    try read ~t:(input_line ch::t) ch with End_of_file -> t

Still not tail recursive because tail calls inside a try block are not 
optimised, so it still segfaults when the file has >100,000 lines on a 64-bit 

Solution is to box and unbox, moving the tail-recursive call outside the try 

  let rec read ?(t=[]) ch =
    match try Some(input_line ch) with End_of_file -> None with
    | Some h -> read ~t:(h::t)
    | None -> t


We really want a File.fold function to fold over the lines of the file, and a 
cons function:

  File.fold cons ch []

I have a much bigger wish list for functions than I do for syntax. I'd like 
the stdlib functions to be tail recursive, more comprehensive and faster...

Dr Jon D Harrop, Flying Frog Consultancy Ltd.
Objective CAML for Scientists