Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] why the "rec" in "let rec"?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Neel Krishnaswami <neelk@a...>
Subject: Re: [Caml-list] why the "rec" in "let rec"?
Garry Hodgson writes:
> 
> something i was always curious about:  why do you need to 
> specify the "rec" in a "let rec" function definition?  as opposed
> to, say, having the compiler figure out when a function is recursive?

It's the simplest way of dealing with the interaction of lexical scope
and recursion. Consider the following examples:

  let f = fun x -> (Printf.printf "#"; x) in
  let f x = f x
  in
  f 5

versus

  let f = fun x -> (Printf.printf "#"; x) in
  let rec f x = f x
  in
  f 5
                
The reference to 'f' in the second function body refers to the f
already in scope. The 'rec' keyword is how you tell the compiler to
ignore that and make it a recursive binding.

So the first example prints "#" and return 5. The second loops
indefinitely.

-- 
Neel Krishnaswami
neelk@alum.mit.edu

-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners