1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
pub use either::Either;
use Either::*;

/// Extention trait to create the Either type from a boolean. Can be implemented on any type.
pub trait Eitherable {
    /// If the boolean is true, returns `Either::Left(left)`. If it is false, returns `Either::Right(right)`.
    /// `left` and `right` are evaluated eagerly. For lazy evaluation, use `either_else()`
    /// # Examples
    ///
    /// ```
    /// use eitherable::*;
    ///
    /// let x = true;
    /// assert_eq!(x.either(1, "right"), Either::Left(1));
    ///
    /// let x = false;
    /// assert_eq!(x.either(1, "right"), Either::Right("right"));
    /// ```
    fn either<L, R>(&self, left: L, right: R) -> Either<L, R>;

    /// Same as `either()`, but the values are lazily evaluated.
    ///
    /// # Examples
    ///
    /// ```
    /// use eitherable::*;
    ///
    /// let x = true;
    /// assert_eq!(x.either_else(|| 1,|| "right"), Either::Left(1));
    ///
    /// let x = false;
    /// assert_eq!(x.either_else(|| 1,|| "right"), Either::Right("right"));
    /// ```
    fn either_else<L, FL: FnOnce() -> L, R, FR: FnOnce() -> R>(
        &self,
        l_func: FL,
        r_func: FR,
    ) -> Either<L, R>;
}

impl Eitherable for bool {
    fn either<L, R>(&self, left: L, right: R) -> Either<L, R> {
        if *self {
            Left(left)
        } else {
            Right(right)
        }
    }

    fn either_else<L, FL: FnOnce() -> L, R, FR: FnOnce() -> R>(
        &self,
        l_func: FL,
        r_func: FR,
    ) -> Either<L, R> {
        if *self {
            Left(l_func())
        } else {
            Right(r_func())
        }
    }
}