diff --git a/lib/ocaml/baseline/bfs.ml b/lib/ocaml/baseline/bfs.ml new file mode 100644 index 00000000..5f5fb66e --- /dev/null +++ b/lib/ocaml/baseline/bfs.ml @@ -0,0 +1,43 @@ +(* Baseline: graph BFS using Queue + Hashtbl visited set. + Returns the count of reachable nodes. *) + +(* Adjacency as an assoc list of (node, neighbors). *) +let graph = + [ ("A", ["B"; "C"]) + ; ("B", ["D"]) + ; ("C", ["D"; "E"]) + ; ("D", ["F"]) + ; ("E", ["F"]) + ; ("F", []) + ] +;; + +let neighbors n = + match List.assoc_opt n graph with + | None -> [] + | Some ns -> ns +;; + +let bfs start = + let visited = Hashtbl.create 16 in + let q = Queue.create () in + Queue.push start q ; + Hashtbl.add visited start true ; + let rec loop () = + if Queue.is_empty q then () + else + let v = Queue.pop q in + List.iter + (fun n -> + if not (Hashtbl.mem visited n) then begin + Hashtbl.add visited n true ; + Queue.push n q + end) + (neighbors v) ; + loop () + in + loop () ; + Hashtbl.length visited +;; + +bfs "A" diff --git a/lib/ocaml/baseline/expected.json b/lib/ocaml/baseline/expected.json index 2c99498f..7ddf40cd 100644 --- a/lib/ocaml/baseline/expected.json +++ b/lib/ocaml/baseline/expected.json @@ -1,5 +1,6 @@ { "anagrams.ml": 3, + "bfs.ml": 6, "btree.ml": 39, "calc.ml": 13, "closures.ml": 315, diff --git a/plans/ocaml-on-sx.md b/plans/ocaml-on-sx.md index 74a565b6..db6ce1b4 100644 --- a/plans/ocaml-on-sx.md +++ b/plans/ocaml-on-sx.md @@ -407,6 +407,10 @@ _Newest first._ binary search tree (`type 'a tree = Leaf | Node of 'a * 'a tree * 'a tree`) with insert + in-order traversal. Tests parametric ADT, recursive match, List.append, List.fold_left. +- 2026-05-08 Phase 5.1 — bfs.ml baseline (20/20 pass). Graph + breadth-first search using Queue + Hashtbl visited-set + List.assoc_opt + + List.iter. Returns the count of reachable nodes (6 for the demo + graph A→B→D→F, A→C→{D,E}, E→F). - 2026-05-08 Phase 1 — type annotations on let-bindings and parens expressions (+4 tests, 473 total). `let NAME [PARAMS] : T = expr` and `(expr : T)` parse and skip the type source. Runtime no-op