I found myself writing the following idiom several times in recent code. It seems like this could be rewritten to something more idiomatic. Can someone help?
The val candidates for comprehension collects a possibly empty collection of values. The if ... expression tests whether the collection is empty and returns the given d else (if not empty) non-destructively appends a reduction of the collection to d .
A problem is that I don’t have a neutral element to give to foldLeft, so I have to call reduce, but I can’t call reduce on an empty collection.
val candidates = for {z <- vertices
a <- d.get(x, z)
b <- m.get(z, y)
} yield semiRingTimes(a, b)
if (candidates.nonEmpty) {
val newMin: R = candidates.reduce(semiRingPlus)
d + ((x -> y) -> newMin)
} else {
d
}
Ahh, so now I understand what reduceOption is for. It appears that it works like reduce but returns None if the container is empty or else Some(reduced-value). Then there is the perverse but useful option.fold. I love it and hate it at the same time.