« Return to Thread: tail recursion

Re: "ocaml_beginners"::[] tail recursion

by Jon Harrop :: Rate this Message:

Reply to Author | View in Thread

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

Note that you already have:

# [1;2;3] @ [4;5;6];;
- : int list = [1; 2; 3; 4; 5; 6]

--
Dr Jon D Harrop, Flying Frog Consultancy Ltd.
http://www.ffconsultancy.com/products/?e

 « Return to Thread: tail recursion