Traditional (not tail-recursive)
let rec append a b =
match a, b with
| [], ys -> ys
| x::xs, ys -> x::append xs ys
With an accumulator (tail-recursive)
let append2 a b =
let rec loop acc = function
| [] -> acc
| x::xs -> loop (x::acc) xs
loop b (List.rev a)
With continuations (tail-recursive)
let append3 a b =
let rec append = function
| cont, [], ys -> cont ys
| cont, x::xs, ys -> append ((fun acc -> cont (x::acc)), xs, ys)
append(id, a, b)
Its pretty straight-forward to convert any non-tail recursive function to recursive with continuations, but I personally prefer accumulators for straight-forward readability.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…