summaryrefslogtreecommitdiff
path: root/receme/src/functor.rs
blob: cd4dac2732a2093a3c06c08aef4c156808a723a0 (plain)
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
//! This file defines the Functor trait.
//!
//! This is the basis of the recursion scheme.
//!
//! More precisely, this file provides two versions of functor traits:
//! one whose `map` function consumes `self`, and one whose `map` does
//! not.

/// A functor can map over its generic parameter.
///
/// It can map from Functor(T) to Functor(S).
pub trait Functor<T> {
    /// The target of the map.
    ///
    /// Since Rust has no higher-kinded polymorphism, we have to
    /// express this type explicitly.
    ///
    /// # Note
    ///
    /// This is a generic associated type, so we need a minimal Rust
    /// version of 1.65, when this feature was first introduced to
    /// stable Rust.
    type Target<S>: Functor<S>;

    /// Map from Functor(T) to Functor(S).
    ///
    /// # Note
    ///
    /// This consumes `self`.  If one wants not to consume `self`,
    /// then consider the trait [`FunctorRef`].
    fn fmap<S>(self, f: impl FnMut(T) -> S) -> Self::Target<S>;
}

impl<T> Functor<T> for Vec<T> {
    type Target<S> = Vec<S>;

    fn fmap<S>(self, f: impl FnMut(T) -> S) -> Self::Target<S> {
        self.into_iter().map(f).collect()
    }
}

/// A functor can map over its generic type parameter.
///
/// It can map from Functor(T) to Functor(S).
///
/// This is similar to [`Functor`], but the
/// [`fmap`][FunctorRef<T>::fmap_ref] method takes a reference and
/// does not consume `self`.
pub trait FunctorRef<T> {
    /// The target of the map.
    ///
    /// Since Rust has no higher-kinded polymorphism, we have to
    /// express this type explicitly.
    ///
    /// # Note
    ///
    /// This is a generic associated type, so we need a minimal Rust
    /// version of 1.65, when this feature was first introduced to
    /// stable Rust.
    type Target<S>: Functor<S>;

    /// Map from Functor(T) to Functor(S).
    ///
    /// # Note
    ///
    /// This does notconsume `self`.  If one wants to consume `self`,
    /// then consider the trait [`Functor`].
    ///
    /// To avoid having to specify the trait when calling the method,
    /// we give it a distinct name.
    fn fmap_ref<S>(&self, f: impl FnMut(T) -> S) -> Self::Target<S>;
}