This is probably too small for a full RFC, but wanted to get some feedback on this idea before working on a PR.
Here’s the more specific thing I needed this week:
fn min_opt<T: Ord>(x: Option<T>, y: Option<T>) -> Option<T> {
match (x, y) {
(Some(x), Some(y)) => Some(cmp::min(x, y)),
(Some(x), _) => Some(x),
(_, Some(y)) => Some(y),
_ => None,
}
}
In my mind, the more general use case here is having two Option
s and wanting to combine them in some way into a new Option
that will pick the non-None
option if there is only one or take an Fn
to combine the two values if both are Some
(it’s also related to currently unstable xor()
in that this is like the inclusive or operation).
So this could be defined as:
fn fold<F>(other: Option<T>, merge: F) -> Option<T> where F: Fn(T, T) -> T {
match (x, y) {
(Some(x), Some(y)) => Some(merge(x, y)),
(Some(x), _) => Some(x),
(_, Some(y)) => Some(y),
_ => None,
}
}
(I suppose there might be value in generalizing merge
to return Option
as well.)
Is this something others have needed as well? Have I missed some straightforward way of expressing this with the current combinators? Does something like this exist in other languages which have Option
-like types?