Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is List.rev acting strangely?

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.

like image 807
Pygmalion Avatar asked Dec 21 '22 01:12

Pygmalion


1 Answers

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 *)
like image 191
Jeffrey Scofield Avatar answered Jan 10 '23 10:01

Jeffrey Scofield