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
The need to specify 'rec' in a recursive function defintion
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2010-02-09 (22:56)
From: Jon Harrop <jon@f...>
Subject: Re: [Caml-list] The need to specify 'rec' in a recursive function defintion
On Tuesday 09 February 2010 22:31:49 Saptarshi Guha wrote:
> Yes, I see  that f isn't recursive, because it simplifies down to
> 2*(x+1) but for a reader(at least myself) it can be bit tricky to
> consume.

But for a writer it can be useful to produce. For example, imagine a function 
in an interpreter that evaluates an expression to a value in the context of a 
set of variable bindings:

  let rec eval vars = function
    | Add(f, g) -> eval vars f + eval vars g
    | Mul(f, g) -> eval vars f * eval vars g

Such functions make a *lot* of recursive calls.

Now imagine you want to inject some code around every external call into 
that "expr" function but not recursive calls, e.g. logging exceptional 
returns. Do you want to change the name of that "expr" function not only in 
its definition but at every recursive call in its body? No.

Fortunately, in OCaml you can just append a definition to supercede "expr" 
without touching the original definition at all:

  let eval vars expr =
    let result = eval vars expr in

This is a useful and common OCaml idiom.

> My experience of reading the /definition/ of a function which 
> includes a call to itself is that it is recursive.

Definitions are often superceded in ML.

> On the stackoverflow post, you mentioned that the British ML branch forces
> different names (since recursion is by default), and though it does pollute
> the namespace, personally I find it easier to read.

You can do that in OCaml as well, if you choose.

Dr Jon Harrop, Flying Frog Consultancy Ltd.