Version française
Home     About     Download     Resources     Contact us    
Browse thread
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: -- (:)
From: John Max Skaller <skaller@o...>
Subject: Re: [Caml-list] How to find out if a function is tail recursive?
> 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 *)
>   ;;

There's a curious 'trick' with tail recursion,
to make the result an argument. That's weird,
but it works. You  pass the result down to the
end as an argument, and it gets returned only
then. For example to count a list:

	let rec count lst acc =
	match lst with
	| [] -> acc
	| h::t -> count t (acc+1)

instead of writing:

	let rec count lst =
	match lst with
	| [] -> 0
	| h :: t -> 1 + count t

which isn't tail recursive.

-- 
John Max Skaller, mailto:skaller@ozemail.com.au
snail:10/1 Toxteth Rd, Glebe, NSW 2037, Australia.
voice:61-2-9660-0850


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