map, filter, reduce in Swift
The functional trio, plus compactMap for the misses.
let legTimes = [512.0, 448.5, 630.0, 505.25]
// map transforms, filter keeps, reduce folds.
let minutes = legTimes.map { $0 / 60 }
print(minutes)
let quickLegs = legTimes.filter { $0 < 520 }
print("Quick legs: \(quickLegs.count)")
let total = legTimes.reduce(0, +)
print("Race time: \(total) s")
// compactMap drops the misses while transforming.
let logged = ["512", "n/a", "448"]
let parsed = logged.compactMap { Double($0) }
print("Parsed \(parsed.count) of \(logged.count)")
How it works
maptransforms every element into a new array.filterkeeps by predicate;reduce(0, +)folds.compactMap { Double($0) }transforms and drops the nils.
Keywords and builtins used here
Doublecountfilterletmapprintreduce
The run, in numbers
- Lines
- 16
- Characters to type
- 482
- Tokens
- 119
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 102 seconds.
Step 3 of 3 in Functions & closures, step 9 of 27 in Language basics.