Lists: map, filter, sum
● Beginner4 min
map changes every item, filter keeps some, sum adds them up, and count, any, all and find ask questions.
fn main() {
const prices = [120, 40, 300, 75]
print(prices.map(p => p * 2))
print(prices.filter(p => p > 100))
print(prices.sum(p => p))
print(prices.count(p => p > 100))
print(prices.any(p => p > 250))
print(prices.all(p => p > 0))
print(prices.find(p => p < 50) ?? 0)
}The program ran and printed:
kavach run pipeline.kav
[240, 80, 600, 150][120, 300]5352truetrue40
Chained, they read like a sentence, and run as a single loop with no list built between the steps:
type Order {
amount: Int
paid: Bool
}
fn main() {
const names = ["asha", "ravi", "meenakshi"]
print(names.map(.upper()))
print(names.filter(.len() > 4))
const orders = [Order(amount: 300, paid: true), Order(amount: 120, paid: false)]
print(orders.filter(.paid).sum(.amount))
}The program ran and printed:
kavach run dot.kav
["ASHA", "RAVI", "MEENAKSHI"]["meenakshi"]300
The first items, and the rest
take(n) gives the first n items, and skip(n) all but them. Asking for more than the list holds gives what there is:
fn main() {
const queue = ["asha", "ravi", "meera", "john", "lin"]
print(queue.take(2))
print(queue.skip(2))
print(queue.skip(2).take(2))
print(queue.take(10).len())
}The program ran and printed:
kavach run take-skip.kav
["asha", "ravi"]["meera", "john", "lin"]["meera", "john"]5
What Kavach does for you
Chains become one loop
xs.map(f).filter(g).sum()runs as a single loop: no list is built between the steps.