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
/*
    Appellation: functor <mod>
    Contrib: FL03 <jo3mccain@icloud.com>
*/
//! # Functor
//!
//! A functor is a type that when mapped over, preserves the structure of the type while applying a function to the values within the type.
//! Functors are useful for modeling the functional effects on values of parameterized data types.
use super::containers::*;
use super::HKT;

pub trait Functor<U>: HKT<U> {
    fn fmap<F>(&self, f: F) -> Self::T
    where
        F: Fn(&Self::C) -> U;
}

macro_rules! functor {
    ($($t:ident),* $(,)?) => {
        $(
            functor!(@impl $t);
        )*
    };
    (@impl $t:ident) => {
       impl<T, U> Functor<U> for $t<T> {
            fn fmap<F>(&self, f: F) -> $t<U>
            where
                F: Fn(&T) -> U,
            {
                $t::new(f(self))
            }
        }
    };
}

#[cfg(any(feature = "std", all(feature = "alloc", no_std)))]
functor!(Arc, Box, Rc);

impl<T, U> Functor<U> for Option<T> {
    fn fmap<F>(&self, f: F) -> Option<U>
    where
        F: Fn(&T) -> U,
    {
        if let Some(ref value) = self {
            return Some(f(value));
        }
        None
    }
}

impl<T, U> Functor<U> for Vec<T> {
    fn fmap<F>(&self, f: F) -> Vec<U>
    where
        F: Fn(&T) -> U,
    {
        let mut result = Vec::with_capacity(self.len());
        for value in self {
            result.push(f(value));
        }
        result
    }
}