monadic_traits/
maybe.rs

1use crate::traits::{Applicative, Functor, Monad};
2use std::ops::{ControlFlow, FromResidual, Try};
3
4/// A simple `Option`-like monad used for FP learning and experimentation.
5///
6/// Supports the `?` operator via nightly `Try` and `FromResidual`.
7#[derive(Debug, Clone, PartialEq)]
8pub enum Maybe<T> {
9    /// A present value
10    Just(T),
11    /// The absence of a value
12    Nothing,
13}
14
15pub struct MaybeTC;
16
17impl Functor for MaybeTC {
18    type Constructor<T> = Maybe<T>;
19
20    fn fmap<A, B, F>(fa: Self::Constructor<A>, f: F) -> Self::Constructor<B>
21    where
22        F: FnOnce(A) -> B,
23    {
24        match fa {
25            Maybe::Just(a) => Maybe::Just(f(a)),
26            Maybe::Nothing => Maybe::Nothing,
27        }
28    }
29}
30
31impl Applicative for MaybeTC {
32    fn pure<T>(x: T) -> Self::Constructor<T> {
33        Maybe::Just(x)
34    }
35
36    fn apply<A, B, F>(ff: Self::Constructor<F>, fa: Self::Constructor<A>) -> Self::Constructor<B>
37    where
38        F: FnOnce(A) -> B,
39    {
40        match (ff, fa) {
41            (Maybe::Just(f), Maybe::Just(a)) => Maybe::Just(f(a)),
42            _ => Maybe::Nothing,
43        }
44    }
45}
46
47impl Monad for MaybeTC {
48    fn bind<A, B, F>(ma: Self::Constructor<A>, f: F) -> Self::Constructor<B>
49    where
50        F: FnOnce(A) -> Self::Constructor<B>,
51    {
52        match ma {
53            Maybe::Just(a) => f(a),
54            Maybe::Nothing => Maybe::Nothing,
55        }
56    }
57}
58
59impl<T> FromResidual<Maybe<!>> for Maybe<T> {
60    fn from_residual(_: Maybe<!>) -> Self {
61        Maybe::Nothing
62    }
63}
64
65impl<T> Try for Maybe<T>
66where
67    Maybe<T>: FromResidual<Maybe<!>>,
68{
69    type Output = T;
70    type Residual = Maybe<!>;
71
72    fn from_output(output: Self::Output) -> Self {
73        Maybe::Just(output)
74    }
75
76    fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
77        match self {
78            Maybe::Just(t) => ControlFlow::Continue(t),
79            Maybe::Nothing => ControlFlow::Break(Maybe::Nothing),
80        }
81    }
82}