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

[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:38) From: Neel Krishnaswami Subject: Re: [Caml-list] How to find out if a function is tail recursive?
```Richard Jones writes:
> I was writing the section on tail recursion in the OCaml tutorial, and
> was surprised to find out that the range function (below) isn't tail
> recursive. Or at least it causes a stack overflow on a
> large-but-not-unreasonable input value.
>
> 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?

A function call is a tail call if it is the last thing that the
function does before returning. In this example:

let rec range a b =
if a > b then
[]
else
a :: range (a+1) b

The two expressions '[]' and 'a :: range (a+1) b' are in tail
position. The recursive call to range is *not* in tail position,
because you need to do the 'a :: <value>' before returning.

You can identify 'tail position' as a purely syntactic criterion, and
then a 'tail call' is any function call in tail position.

With the function definition

let f x = <expr>

<expr> is an expression in tail position.

If you have an expression <expr> in tail position, then

If <expr> = <f> <x>, then:

o neither subexpression <f> nor <x> is in tail position,
o the call '<f> <x>' is in tail position

If <expr> = if <test>
then <e_1>
else <e_2>, then:

o <test> is not in tail position
o <e_1> and <e_2> are in tail position

If <expr> = match <m> with
| pat -> <e_1>
| ...
| pat -> <e_n>, then:

o <m> is not in tail position
o <e_1> ... <e_n> are in tail position.

If <expr> = begin
<e_1>;
...
<e_n-1>;
<e_n>
end, then:

o <e1> ... <e_n-1> are not in tail position
o <e_n> is in tail position

If <expr> = try <body> with exn -> <handler>, then:

o <body> is not in tail position
o <handler> is in tail position

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

```