« Return to Thread: tail recursion

"ocaml_beginners"::[] Re: tail recursion

by remi.vanicat :: Rate this Message:

Reply to Author | View in Thread

Fabrice Marchant <fabrice.marchant@...> writes:
> let append =
>   let rec rappend = function
>       [] -> id
>     | h::t -> rappend t <<- (cons h) in
>     rappend <<- List.rev

There is a problem on this code: it is not polymorphic enough, just
try

rappend [2] [3];;
rappend [None] [];;

if you want a fully polymorphic version, you need to wrote it as :
let append l =
   let rec rappend = function
       [] -> id
     | h::t -> rappend t <<- (cons h) in
     (rappend <<- List.rev) l

which defeat your goal.

>
>   It is the opportunity to ask this :
> I wonder if this later is perfectly equivalent to the former ?

Not sure

> Is it absolutely true that the 3 tiny functions id, cons and ( <<- )
> will be inlined without any efficiency loss ?

Not sure, well, not with bytecode, I don't know with ocamlopt, you
should test (option -S to ask ocamlopt for the assembly code).

--
Rémi Vanicat

 « Return to Thread: tail recursion