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.