Skip to content

Commit 771bd5e

Browse files
committed
implement optimization on intersection op
1 parent c6ec3f4 commit 771bd5e

File tree

1 file changed

+31
-11
lines changed

1 file changed

+31
-11
lines changed

stdlib/lm_set.ml

Lines changed: 31 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1092,10 +1092,11 @@ struct
10921092
| [], _ -> size, ys
10931093
| _, [] -> size, xs
10941094
| x :: tx, y :: ty ->
1095-
if Ord.compare x y = 0
1095+
let comp = Ord.compare x y in
1096+
if comp = 0
10961097
then let s, rs = merge (pred size) tx ty in
10971098
s, x :: rs
1098-
else if Ord.compare x y < 0
1099+
else if comp < 0
10991100
then let s, rs = merge size tx ys in
11001101
s, x :: rs
11011102
else let s, rs = merge size xs ty in
@@ -1253,19 +1254,38 @@ struct
12531254
s) (1, []) s
12541255
in treeify n l
12551256

1257+
let rec distinct size xs ys =
1258+
match xs, ys with
1259+
[], _ -> size, []
1260+
| _, [] -> size, []
1261+
| x :: tx, y :: ty ->
1262+
let comp = Ord.compare x y in
1263+
if comp = 0
1264+
then let s, rs = distinct (succ size) tx ty in
1265+
s, x :: rs
1266+
else if comp < 0
1267+
then distinct size tx ys
1268+
else distinct size xs ty
1269+
12561270
let inter s1 s2 =
12571271
let size1 = cardinality s1 in
12581272
let size2 = cardinality s2 in
1259-
let s1, s2 =
1260-
if size1 < size2 then
1261-
s1, s2
1273+
let comp = compare_height size1 size2 in
1274+
let n, l =
1275+
if comp = 0 then
1276+
distinct 1 (to_list s1) (to_list s2)
12621277
else
1263-
s2, s1 in
1264-
let n, l = fold_r (fun s3 x ->
1265-
if mem s2 x then
1266-
add_item x s3
1267-
else
1268-
s3) (1, []) s1
1278+
let s1, s2 =
1279+
if comp < 0 then
1280+
s1, s2
1281+
else
1282+
s2, s1
1283+
in
1284+
fold_r (fun s3 x ->
1285+
if mem s2 x then
1286+
add_item x s3
1287+
else
1288+
s3) (1, []) s1
12691289
in treeify n l
12701290

12711291
let partition pred s =

0 commit comments

Comments
 (0)