@@ -1961,6 +1961,42 @@ impl<T> Option<T> {
19611961 _ => None ,
19621962 }
19631963 }
1964+
1965+ /// Reduces two options into one, using the provided function if both are `Some`.
1966+ ///
1967+ /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some(f(s, o))`.
1968+ /// Otherwise, if only one of `self` and `other` is `Some`, that one is returned.
1969+ /// If both `self` and `other` are `None`, `None` is returned.
1970+ ///
1971+ /// # Examples
1972+ ///
1973+ /// ```
1974+ /// #![feature(option_reduce)]
1975+ ///
1976+ /// let s12 = Some(12);
1977+ /// let s17 = Some(17);
1978+ /// let n = None;
1979+ /// let f = |a, b| a + b;
1980+ ///
1981+ /// assert_eq!(s12.reduce(s17, f), Some(29));
1982+ /// assert_eq!(s12.reduce(n, f), Some(12));
1983+ /// assert_eq!(n.reduce(s17, f), Some(17));
1984+ /// assert_eq!(n.reduce(n, f), None);
1985+ /// ```
1986+ #[ unstable ( feature = "option_reduce" , issue = "144273" ) ]
1987+ pub fn reduce < U , R , F > ( self , other : Option < U > , f : F ) -> Option < R >
1988+ where
1989+ T : Into < R > ,
1990+ U : Into < R > ,
1991+ F : FnOnce ( T , U ) -> R ,
1992+ {
1993+ match ( self , other ) {
1994+ ( Some ( a ) , Some ( b ) ) => Some ( f ( a , b ) ) ,
1995+ ( Some ( a ) , _ ) => Some ( a. into ( ) ) ,
1996+ ( _ , Some ( b ) ) => Some ( b. into ( ) ) ,
1997+ _ => None ,
1998+ }
1999+ }
19642000}
19652001
19662002impl <T , U > Option < ( T , U ) > {
0 commit comments