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

Re: [Caml-list] How to find out if a function is tail recursive?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
 Date: 2003-06-12 (14:43) From: Luc Maranget Subject: Re: [Caml-list] How to find out if a function is tail recursive?
```>
> > let rec range a b =
> >   if a > b then []
> >   else a :: range (a+1) b
> >   ;;
> >
> > let list = range 1 1000000;;
> >
> > Printf.printf "length = %d\n" (List.length list);;
> >
> > Can you tell me why this function isn't tail recursive, and
> > share any useful tips on how to tell whether a function is or
> > is not tail recursive?
>
> The recursive call to range is not the result for its
> caller.  Instead, the result of recursive call is
> an argument to the cons (the :: operator).
>
> -- Paul

Hence, here is a tail-recursive range function.

let rec do_range a b r =
if a > b then r
else do_range a (b-1) (b::r) (* tail-rec call *)
;;

let range a b = do_range a b []
;;

--Luc

-------------------
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

```