Map.filter
func Map.filter[K, V](m: Map[K, V], f: func(Entry[K, V]): bool): Map[K, V]Map.filter returns a new map holding the entries of m that f accepts, in the order of m.
Details
- Returns a new map;
mis unchanged, even whenfaccepts every entry. - Calls
fonce per entry, in insertion order.
Basic examples
Keep the entries whose value passes a test:
let stock = Map{ apples: 3, pears: 0, plums: 7 }
Map.filter(stock, { x.value > 0 }) // Map{ "apples": 3, "plums": 7 }Keep the entries whose key passes a test:
let stock = Map{ apples: 3, pears: 0, plums: 7 }
Map.filter(stock, { x.key.startsWith("p") }) // Map{ "pears": 0, "plums": 7 }Scope
An empty map gives an empty map, and so does a predicate that accepts nothing:
let empty: Map[string, int] = Map{}
empty.filter({ true }) // Map{}
Map{ a: 1, b: 2 }.filter({ false }) // Map{}The result keeps the order of m, which is the order its keys were first inserted:
let m = Map{ b: 2, a: 1, c: 3 }
m.filter({ x.key != "a" }) // Map{ "b": 2, "c": 3 }Keys can be records:
type Point = { x: int, y: int }
let grid = Map{ Point{ x: 0, y: 0 }: "start", Point{ x: 2, y: 1 }: "tree", Point{ x: 0, y: 3 }: "rock" }
grid.filter({ x.key.x == 0 }) // Map{ Point{ x: 0, y: 0 }: "start", Point{ x: 0, y: 3 }: "rock" }Values can be a union; pick one member with is:
type Open = {}
type Closed = { reason: string }
type State = Open | Closed
let doors: Map[string, State] = Map{ front: Open{}, back: Closed{ reason: "locked" } }
doors.filter({ x.value is Closed }) // Map{ "back": Closed{ reason: "locked" } }Drop the entries whose value is null:
let ages = Map{ "Ann": 31, "Bob": null, "Cid": 27 }
ages.filter({ x.value != null }) // Map{ "Ann": 31, "Cid": 27 }Pass a named function that takes an Entry:
func isPositive(e: Entry[string, int]): bool { e.value > 0 }
Map{ a: 1, b: -1, c: 5 }.filter(isPositive) // Map{ "a": 1, "c": 5 }An anonymous function can destructure the entry into its key and value:
let m = Map{ a: 1, b: 2, c: 3 }
m.filter(func(e: Entry[string, int]): bool {
let { key, value } = e
value > 1 && key != "c"
}) // Map{ "b": 2 }Call it through . or in a pipe:
let stock = Map{ apples: 3, pears: 0, plums: 7 }
stock.filter({ x.value < 5 }) // Map{ "apples": 3, "pears": 0 }
stock | Map.filter({ x.key == "plums" }) // Map{ "plums": 7 }Applications
Hide the keys named in a set before logging form data:
let hidden = Set.of(["password", "token"])
let form = Map{ user: "ann", password: "hunter2", token: "abc" }
form.filter({ !hidden.has(x.key) }) // Map{ "user": "ann" }Print the words of two or more letters that occur at least three times:
let counts = Map{ "the": 12, "ant": 3, "a": 9, "hill": 1 }
for e in counts.filter({ x.value >= 3 && x.key.length() > 1 }).entries() {
println("${e.key} ${e.value}")
}the 12
ant 3Split a map in two with a predicate and its negation:
let scores = Map{ Ann: 91, Bob: 58, Cid: 74 }
let passed = scores.filter({ x.value >= 60 })
let failed = scores.filter({ x.value < 60 })
passed // Map{ "Ann": 91, "Cid": 74 }
failed // Map{ "Bob": 58 }Properties and relations
Map.filter gives the same map as filtering the entries and building a map from them:
let m = Map{ a: 1, b: 2, c: 3 }
let f: func(Entry[string, int]): bool = { x.value % 2 == 1 }
assert(Map.filter(m, f) == Map.fromEntries(Map.entries(m).filter(f)))
assert(Map.keys(Map.filter(m, f)) == ["a", "c"])Filtering by f and by its negation splits m with nothing lost:
let m = Map{ a: 1, b: 2, c: 3, d: 4 }
let f: func(Entry[string, int]): bool = { x.value > 2 }
let yes = m.filter(f)
let no = m.filter({ !f(x) })
assert(yes.size() + no.size() == m.size())
assert(Map.merge(yes, no) == m)f runs once per entry, in insertion order:
let m = Map{ b: 2, a: 1, c: 3 }
let seen: Array[string] = []
let big = m.filter(func(e: Entry[string, int]): bool {
seen.push(e.key)
e.value > 1
})
assert(seen == ["b", "a", "c"])
assert(big == Map{ b: 2, c: 3 })Filtering twice by the same predicate changes nothing the second time:
let m = Map{ a: 1, b: 2, c: 3 }
let once = m.filter({ x.value != 2 })
assert(once.filter({ x.value != 2 }) == once)The result is a new map even when it holds every entry, so changing it leaves m as it was:
let m = Map{ a: 1, b: 2 }
let all = m.filter({ true })
assert(all == m)
assert(!Map.same(all, m))
all["c"] = 3
assert(m.size() == 2)Possible issues
Map.filter returns a new map and leaves m as it was. A call whose result is thrown away does not change m; assign the result, or use Map.remove to change m in place:
let stock = Map{ apples: 3, pears: 0 }
stock.filter({ x.value > 0 })
println(stock)Map{ "apples": 3, "pears": 0 }The predicate takes one Entry, not a key and a value:
let stock = Map{ apples: 3, pears: 0 }
let inStock = stock.filter(func(k: string, v: int): bool { v > 0 })
// error: cannot use func(string, int): bool where func(Entry[string, int]): bool is expectedThe predicate must return a bool. Ant has no truthy values, so an int is a compile error:
let stock = Map{ apples: 3, pears: 0 }
let inStock = stock.filter({ x.value }) // error: cannot use int where bool is expectedThe result keeps the value type of m. Filtering out null gives a Map[string, int | null], not a Map[string, int]:
let ages = Map{ "Ann": 31, "Bob": null }
let kept = ages.filter({ x.value != null })
let known: Map[string, int] = kept // error: cannot use Map[string, int | null] where Map[string, int] is expectedBuild the map in a loop instead, where the test on value narrows it to int:
let ages = Map{ "Ann": 31, "Bob": null, "Cid": 27 }
let known: Map[string, int] = Map{}
for { key, value } in ages {
if value != null { known[key] = value }
}
known // Map{ "Ann": 31, "Cid": 27 }See also
Map.map, Map.entries, Map.fromEntries, Map.remove, Map.merge, Array.filter, Entry
