From c6db0d49de9a3b8b0abd72b9c3d6b4c2fcc0065b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ulysse=20G=C3=A9rard?= Date: Fri, 10 Jan 2025 11:44:20 +0100 Subject: [PATCH] Refactor: use the language's references Suggested-by: xvw --- src/index-format/union_find.ml | 40 ++++++++++++++++++---------------- 1 file changed, 21 insertions(+), 19 deletions(-) diff --git a/src/index-format/union_find.ml b/src/index-format/union_find.ml index 246c14752..e2d2bb47d 100644 --- a/src/index-format/union_find.ml +++ b/src/index-format/union_find.ml @@ -1,12 +1,12 @@ type 'a content = | Root of { mutable value : 'a; mutable rank : int } | Link of { mutable parent : 'a element } -and 'a element = { mutable content : 'a content } +and 'a element = 'a content ref -let make value = { content = Root { value; rank = 0 } } +let make value = ref (Root { value; rank = 0 }) let rec find x = - match x.content with + match !x with | Root _ -> x | Link ({ parent; _ } as link) -> let root = find parent in @@ -16,23 +16,25 @@ let rec find x = let union ~f x y = let x = find x in let y = find y in - match (x, y) with - | x, y when x == y -> x - | ( { content = Root ({ rank = rank_x; value = value_x } as root_x); _ }, - { content = Root ({ rank = rank_y; value = value_y } as root_y); _ } ) -> - let new_value = f value_x value_y in - if rank_x < rank_y then ( - x.content <- Link { parent = y }; - root_y.value <- new_value; - y) - else ( - y.content <- Link { parent = x }; - root_x.value <- new_value; - if rank_x = rank_y then root_x.rank <- root_x.rank + 1; - x) - | _ -> assert false + if x == y then x + else begin + match (!x, !y) with + | ( Root ({ rank = rank_x; value = value_x } as root_x), + Root ({ rank = rank_y; value = value_y } as root_y) ) -> + let new_value = f value_x value_y in + if rank_x < rank_y then ( + x := Link { parent = y }; + root_y.value <- new_value; + y) + else ( + y := Link { parent = x }; + root_x.value <- new_value; + if rank_x = rank_y then root_x.rank <- root_x.rank + 1; + x) + | _ -> assert false + end let get elt = - match (find elt).content with + match !(find elt) with | Root { value; _ } -> value | Link _ -> assert false