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
/*
    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::HKT;
use std::rc::Rc;
use std::sync::Arc;

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

impl<T, U> Functor<U> for Arc<T> {
    fn fmap<F>(&self, f: F) -> Arc<U>
    where
        F: Fn(&T) -> U,
    {
        Arc::new(f(self))
    }
}

impl<T, U> Functor<U> for Box<T> {
    fn fmap<F>(&self, f: F) -> Box<U>
    where
        F: Fn(&T) -> U,
    {
        Box::new(f(self))
    }
}

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 Rc<T> {
    fn fmap<F>(&self, f: F) -> Rc<U>
    where
        F: Fn(&T) -> U,
    {
        Rc::new(f(self))
    }
}

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
    }
}