I'm new to OCaml and attempting to implement List.append
as a learning exercise. This is what I have:
let rec append a b =
match (List.rev a) with
[] -> b
| x:: xs -> append xs (x::b)
This seems to work until argument a
has more than two elements. Example:
# append [1;2] [3;4]
- : int list = [1; 2; 3; 4]
# append [1;2;3] [4;5;6]
- : int list = [2; 1; 3; 4; 5; 6]
What's going on here? I've checked, and List.rev [1;2;3]
returns int list = [3; 2; 1]
. I know my implementation is naïve and not (yet) lazy, but it seems like it should work.
If you think about it, you are reversing your first list quite a few times. Probably more than you wanted to.
You can see what's happening if you follow the steps of an example.
append [1; 2; 3] []
(* match binds x to 3, xs to [2; 1] *)
append [2; 1] [3]
(* match binds x to 1, xs to [2] *)
append [2] [1; 3]
(* match binds x to 2, xs to [] *)
append [] [2; 1; 3]
(* done *)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With