ocaml: phase 6 Stack + Queue modules (+5 tests, 430 total)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 35s

Stack: ref-holding-list LIFO. push/pop/top/length/is_empty/clear.
Queue: two-list (front, back) amortised O(1) queue. push/pop/length/
is_empty/clear. Both in OCaml syntax in runtime.sx.
This commit is contained in:
2026-05-08 17:03:32 +00:00
parent ffa74399fd
commit f05d405bac
3 changed files with 71 additions and 0 deletions

View File

@@ -366,6 +366,48 @@
let printf fmt = print_string fmt
end ;;
module Stack = struct
let create () = ref []
let push x s = s := x :: !s
let pop s =
match !s with
| [] -> failwith \"Stack.pop: empty\"
| h :: t -> s := t ; h
let top s =
match !s with
| [] -> failwith \"Stack.top: empty\"
| h :: _ -> h
let is_empty s = !s = []
let length s = List.length !s
let clear s = s := []
end ;;
module Queue = struct
(* Simple two-list amortized queue: (front, back). pop drains
front; refill from rev back when front is empty. *)
let create () = ref ([], [])
let push x q =
let p = !q in
q := (List.append [] (match p with (f, b) -> f), x :: (match p with (_, b) -> b))
let length q =
let p = !q in
let f = match p with (f, _) -> f in
let b = match p with (_, b) -> b in
List.length f + List.length b
let is_empty q = length q = 0
let pop q =
let p = !q in
let f = match p with (f, _) -> f in
let b = match p with (_, b) -> b in
match f with
| h :: t -> q := (t, b) ; h
| [] ->
(match List.rev b with
| [] -> failwith \"Queue.pop: empty\"
| h :: t -> q := (t, []) ; h)
let clear q = q := ([], [])
end ;;
module Buffer = struct
let create _ = ref []
let add_string b s = b := s :: !b