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 (21:54)
From: Guillaume Yziquel <guillaume.yziquel@c...>
Subject: Re: [Caml-list] The need to specify 'rec' in a recursive function defintion
Saptarshi Guha a écrit :
> Hello,
>  I was wondering why recursive functions need to be specified with
> "rec". According to Practical Ocaml, to "inform the compiler that the function
> exists". But when entering the function definition, can't the compiler note that
> the function is being defined so that when it sees the function calling itself,
> it wont say "Unbound value f"?

Essentially, the fact that "rec" means anything is mostly due to the 
fact that you want to be able to redefine stuff.

> let f = fun x -> x + 1
> let f x = f (f x)

is valid in ocaml, and you're function f is the function that adds 2.


> let rec f x = f (f x)

has a completely different meaning.

If you avoided the use of rec, saying "if unbound, assume rec", then the 

let f x = f (f x)

has two entirely different meaning, depending on whether f is defined 
before or not.

That would be quite a chaotic feature.

> Wouldn't one of way of detecting a recursive function would be to see
> if the indeed the function calls itself?

No. Because you never know if you intended to call the function 
recursively, or if you intended to call an homonymous function you 
defined before.

All the best,

      Guillaume Yziquel