On Mon, 10 Mar 2008, Jon Harrop wrote:
> On Monday 10 March 2008 17:49:06 stevewirts wrote:
>> could anyone tell me if this is tail recursive?
>>
>> let append l1 l2 =
>> let rl1 = List.rev l1 in
>> let rec rappend l1 l2 =
>> if l1 = [] then l2
>> else
>> let hd = List.hd l1 in
>> let tl = List.tl l1 in
>> let larger = hd :: l2 in
>> rappend tl larger
>> in rappend rl1 l2;;
>>
>> # append [1;2;3] [4;5;6];;
>> - : int list = [1; 2; 3; 4; 5; 6]
>
> That is tail recursive but you can write it much more elegantly using pattern
> matching:
>
> let rec rev_append l1 l2 =
> match l1, l2 with
> | [], l2 -> l2
> | hd::tl, l2 -> rev_append tl (hd::l2);;
>
> let append l1 l2 =
> rev_append (List.rev l1) l2;;
Or even:
let append l1 l2 =
rev_append (rev_append l1 []) l2;;
Martin
--
http://wink.com/profile/mjambonhttp://martin.jambon.free.fr