How can I implement a tail-recursive list append?
Posted
by martingw
on Stack Overflow
See other posts from Stack Overflow
or by martingw
Published on 2010-05-19T16:33:27Z
Indexed on
2010/05/19
17:00 UTC
Read the original article
Hit count: 172
A simple append function like this (in F#):
let rec app s t =
match s with
| [] -> t
| (x::ss) -> x :: (app ss t)
will crash when s becomes big, since the function is not tail recursive. I noticed that F#'s standard append function does not crash with big lists, so it must be implemented differently. So I wondered: How does a tail recursive definition of append look like? I came up with something like this:
let rec comb s t =
match s with
| [] -> t
| (x::ss) -> comb ss (x::t)
let app2 s t = comb (List.rev s) t
which works, but looks rather odd. Is there a more elegant definition?
© Stack Overflow or respective owner