~williewillus/persistent

b27a1a2b4f7f0d2d0f49ec7fb654d198d28e02b0 — Vincent Lee 1 year, 3 days ago c3847c9
Add Vector.of_seq and Vector.equal
3 files changed, 36 insertions(+), 8 deletions(-)

M lib/vector.ml
M lib/vector.mli
M test/vectorTest.ml
M lib/vector.ml => lib/vector.ml +24 -0
@@ 207,7 207,31 @@ let update (t : 'a t) (i : int) (value : 'a) : 'a t =
    in
    { t with root = rebuild t.root t.height }

let of_seq (xs : 'a Seq.t) : 'a t =
  Seq.fold_left append (empty ()) xs

(** Dead-simple Sequence implementation.
    TODO: optimize by holding onto the leaf so we don't have to walk down every time *)
let to_seq (t : 'a t) : 'a Seq.t =
  Seq.init t.count (fun i -> nth t i)

let equal
      (eq : 'a -> 'a -> bool)
      (a : 'a t)
      (b : 'a t) : bool =
  if a == b then
    true
  else
    if Int.equal a.count b.count then
      (* TODO: optimize with tree structure instead of nth? *)
      let rec check index =
        let reached_end = index >= a.count in
        if reached_end then
          true
        else
          let this_element_equal = eq (nth a index) (nth b index) in
          this_element_equal && (check[@tailcall]) (index + 1)
      in
      check 0
    else
      false

M lib/vector.mli => lib/vector.mli +4 -0
@@ 17,4 17,8 @@ val append : 'a t -> 'a -> 'a t

val update : 'a t -> int -> 'a -> 'a t

val of_seq : 'a Seq.t -> 'a t

val to_seq : 'a t -> 'a Seq.t

val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool

M test/vectorTest.ml => test/vectorTest.ml +8 -8
@@ 1,21 1,21 @@
module Vector = Persistent.Vector

(* Just spams a bunch of numbers in and asserts we get the same stuff back out
   Should cover pretty much all of the insertion logic.
   Should cover pretty much all of the insertion logic and also of_seq/to_seq
 *)
let test_insert_sanity () =
let test_insert_seq_sanity () =
  let num = 1 lsl 20 in
  let v = Seq.init num Fun.id
          |> Seq.fold_left
               (fun acc i -> Vector.append acc i)
               (Vector.empty ())
  in
  let v = Seq.init num Fun.id |> Vector.of_seq in
  let expected = List.of_seq (Seq.init num Fun.id) in
  let actual = List.of_seq (Vector.to_seq v) in
  assert (List.equal Int.equal actual expected)

(* Tests that the vector is actually persistent, in that previous values are still usable
   and have the same value after performing updates
 *)

let all_tests = [
    ("Insert Sanity", test_insert_sanity)
    ("Insert and Seq Sanity", test_insert_seq_sanity)
  ]

let main () =