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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
    Appellation: monad <mod>
    Contrib: FL03 <jo3mccain@icloud.com>
*/
use super::Applicative;
use super::HKT;

use super::containers::*;

pub trait Monad<U>: Applicative<U> {
    fn return_(x: U) -> Self::T
    where
        Self: HKT<U, C = U>,
    {
        Self::pure_(x)
    }

    fn bind<F>(&self, fs: F) -> Self::T
    where
        F: FnMut(&Self::C) -> Self::T;

    fn join<T>(&self) -> T
    where
        Self: HKT<U, T = T, C = T>,
        T: Clone,
    {
        self.bind(|x| x.clone())
    }
}

impl<T, U> Monad<U> for Arc<T> {
    fn bind<F>(&self, mut fs: F) -> Arc<U>
    where
        F: FnMut(&T) -> Arc<U>,
    {
        fs(self)
    }
}

impl<T, U> Monad<U> for Box<T> {
    fn bind<F>(&self, mut fs: F) -> Box<U>
    where
        F: FnMut(&T) -> Box<U>,
    {
        fs(self)
    }
}

impl<T, U> Monad<U> for Option<T> {
    fn bind<F>(&self, mut fs: F) -> Option<U>
    where
        F: FnMut(&T) -> Option<U>,
    {
        match *self {
            Some(ref value) => fs(value),
            None => None,
        }
    }
}

impl<T, U> Monad<U> for Rc<T> {
    fn bind<F>(&self, mut fs: F) -> Rc<U>
    where
        F: FnMut(&T) -> Rc<U>,
    {
        fs(self)
    }
}

impl<T, U> Monad<U> for Vec<T> {
    fn bind<F>(&self, mut fs: F) -> Vec<U>
    where
        F: FnMut(&T) -> Vec<U>,
    {
        let mut v = Vec::new();
        for x in self {
            v.extend(fs(x));
        }
        v
    }
}