Skip to content

Commit 8c1a687

Browse files
committed
optimize set intersection and union
1 parent d3b380c commit 8c1a687

File tree

1 file changed

+16
-10
lines changed

1 file changed

+16
-10
lines changed

crates/compiler/builtins/roc/Dict.roc

+16-10
Original file line numberDiff line numberDiff line change
@@ -579,7 +579,10 @@ values = \@Dict { data } ->
579579
## ```
580580
insertAll : Dict k v, Dict k v -> Dict k v where k implements Hash & Eq
581581
insertAll = \xs, ys ->
582-
walk ys xs insert
582+
if len ys > len xs then
583+
insertAll ys xs
584+
else
585+
walk ys xs insert
583586

584587
## Combine two dictionaries by keeping the [intersection](https://en.wikipedia.org/wiki/Intersection_(set_theory))
585588
## of all the key-value pairs. This means that we keep only those pairs
@@ -601,15 +604,18 @@ insertAll = \xs, ys ->
601604
## ```
602605
keepShared : Dict k v, Dict k v -> Dict k v where k implements Hash & Eq
603606
keepShared = \xs, ys ->
604-
walk
605-
xs
606-
(empty {})
607-
(\state, k, v ->
608-
if contains ys k then
609-
insert state k v
610-
else
611-
state
612-
)
607+
if len ys < len xs then
608+
keepShared ys xs
609+
else
610+
walk
611+
xs
612+
(withCapacity (len xs))
613+
(\state, k, v ->
614+
if contains ys k then
615+
insert state k v
616+
else
617+
state
618+
)
613619

614620
## Remove the key-value pairs in the first input that are also in the second
615621
## using the [set difference](https://en.wikipedia.org/wiki/Complement_(set_theory)#Relative_complement)

0 commit comments

Comments
 (0)