Mercurial > lbo > hg > ocaml-helloworld
changeset 7:3ff160c43d45 default tip
list playground
author | Lewin Bormann <lbo@spheniscida.de> |
---|---|
date | Sun, 24 Sep 2023 18:16:08 +0200 |
parents | 951efd2df6a3 |
children | |
files | dune list/List_queue.ml list/dune |
diffstat | 3 files changed, 93 insertions(+), 1 deletions(-) [+] |
line wrap: on
line diff
--- a/dune Sun Jul 23 18:29:01 2023 +0200 +++ b/dune Sun Sep 24 18:16:08 2023 +0200 @@ -38,7 +38,6 @@ (inline_tests) (preprocess (pps ppx_inline_test ppx_assert ppx_sexp_value)) (libraries myqueue base)) - (env (dev (flags (:standard -w -32-33))))
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/list/List_queue.ml Sun Sep 24 18:16:08 2023 +0200 @@ -0,0 +1,83 @@ +module List = struct + type 'a node = { + mutable prev : 'a node option; + mutable next : 'a node option; + data : 'a; + } + + type 'a t = { + mutable head : 'a node option; + mutable tail : 'a node option; + mutable length : int; + } + + let node data = { prev = None; next = None; data } + let empty () = { head = None; tail = None; length = 0 } + + let add l e = + let n = node e in + match l.head with + | None -> + l.head <- Some n; + l.tail <- Some n; + l.length <- l.length + 1 + | Some h -> + n.next <- l.head; + h.prev <- Some n; + l.head <- Some n; + l.length <- l.length + 1 + + let pop l = + match l.tail with + | None -> None + | Some n -> + l.tail <- n.prev; + n.prev <- None; + l.length <- l.length - 1; + Some n.data + + let rec of_list = function + | [] -> empty () + | x :: xs -> + let l = of_list xs in + add l x; + l + + let rec to_list = function + | { head = Some h; tail; length } -> + h.data :: to_list { head = h.next; tail; length = length - 1 } + | { head = None; _ } -> [] + + let length l = l.length +end + +let%test "list_length" = + let l = List.empty () in + let m = List.empty () in + let eq = Int.equal in + List.add m 222; + List.add m 333; + eq (List.length l) 0 && eq (List.length m) 2 + +let%test "list_order" = + let l = List.empty () in + List.add l 1; + List.add l 2; + Option.equal Int.equal (List.pop l) (Some 1) + +let%test "of_list" = + let l = List.of_list [ 1; 2; 3; 4 ] in + let eq x y = Option.equal Int.equal x y in + let p0 = List.length l == 4 in + let p1 = eq (List.pop l) (Some 4) in + let p2 = eq (List.pop l) (Some 3) in + let p3 = eq (List.pop l) (Some 2) in + let p4 = eq (List.pop l) (Some 1) in + let p5 = eq (List.pop l) None in + p0 && p1 && p2 && p3 && p4 && p5 + +let%test "to_list" = + let orig = [ 1; 2; 3; 4 ] in + let l = List.of_list orig in + let ll = List.to_list l in + Base.List.equal Int.equal orig ll