Skip to content

Commit

Permalink
Implement mapFilter using foldLeft instad of iter
Browse files Browse the repository at this point in the history
  • Loading branch information
s-and-witch committed Oct 14, 2024
1 parent 11613a5 commit 3b1471e
Showing 1 changed file with 6 additions and 10 deletions.
16 changes: 6 additions & 10 deletions src/PersistentOrderedMap.mo
Original file line number Diff line number Diff line change
Expand Up @@ -602,19 +602,15 @@ module {
};

public func mapFilter<K, V1, V2>(t : Map<K, V1>, compare : (K, K) -> O.Order, f : (K, V1) -> ?V2) : Map<K, V2>{
var map = #leaf : Map<K, V2>;
for(kv in iter(t, #fwd))
{
switch(f kv){
case null {};
case (?v1) {
// The keys still are monotonic, so we can
// merge trees using `append` and avoid compare here
map := put(map, compare, kv.0, v1);
func combine(key : K, value1 : V1, acc : Map<K, V2>) : Map<K, V2> {
switch (f(key, value1)){
case null { acc };
case (?value2) {
put(acc, compare, key, value2)
}
}
};
map
foldLeft(t, #leaf, combine)
};

public func get<K, V>(t : Map<K, V>, compare : (K, K) -> O.Order, x : K) : ?V {
Expand Down

0 comments on commit 3b1471e

Please sign in to comment.