Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions library/core/src/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1961,6 +1961,42 @@ impl<T> Option<T> {
_ => None,
}
}

/// Reduces two options into one, using the provided function if both are `Some`.
///
/// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some(f(s, o))`.
/// Otherwise, if only one of `self` and `other` is `Some`, that one is returned.
/// If both `self` and `other` are `None`, `None` is returned.
///
/// # Examples
///
/// ```
/// #![feature(option_reduce)]
///
/// let s12 = Some(12);
/// let s17 = Some(17);
/// let n = None;
/// let f = |a, b| a + b;
///
/// assert_eq!(s12.reduce(s17, f), Some(29));
/// assert_eq!(s12.reduce(n, f), Some(12));
/// assert_eq!(n.reduce(s17, f), Some(17));
/// assert_eq!(n.reduce(n, f), None);
/// ```
#[unstable(feature = "option_reduce", issue = "144273")]
pub fn reduce<U, R, F>(self, other: Option<U>, f: F) -> Option<R>
where
T: Into<R>,
U: Into<R>,
F: FnOnce(T, U) -> R,
{
match (self, other) {
(Some(a), Some(b)) => Some(f(a, b)),
(Some(a), _) => Some(a.into()),
(_, Some(b)) => Some(b.into()),
_ => None,
}
}
}

impl<T, U> Option<(T, U)> {
Expand Down
1 change: 1 addition & 0 deletions library/coretests/tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@
#![feature(never_type)]
#![feature(next_index)]
#![feature(numfmt)]
#![feature(option_reduce)]
#![feature(pattern)]
#![feature(pointer_is_aligned_to)]
#![feature(portable_simd)]
Expand Down
Loading