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
82
83
84
85
86
87
use itertools::Itertools;
pub trait Kind1To1 {
type Constructor<S>;
}
pub trait Functor<T>: Kind1To1 {
fn fmap<S>(self, f: impl FnMut(T) -> S) -> Self::Constructor<S>;
}
pub trait FunctorRef<T>: Kind1To1 {
fn fmap_ref<S>(&self, f: impl FnMut(&T) -> S) -> Self::Constructor<S>;
}
impl<T> Kind1To1 for Vec<T> {
type Constructor<S> = Vec<S>;
}
impl<T> Functor<T> for Vec<T> {
fn fmap<S>(self, f: impl FnMut(T) -> S) -> Vec<S> {
self.into_iter().map(f).collect()
}
}
impl<T> FunctorRef<T> for Vec<T> {
fn fmap_ref<S>(&self, f: impl FnMut(&T) -> S) -> Vec<S> {
self.iter().map(f).collect()
}
}
impl<T, const N: usize> Kind1To1 for [T; N] {
type Constructor<S> = [S; N];
}
impl<T, const N: usize> Functor<T> for [T; N] {
fn fmap<S>(self, f: impl FnMut(T) -> S) -> [S; N] {
self.map(f)
}
}
impl<T, const N: usize> FunctorRef<T> for [T; N] {
fn fmap_ref<S>(&self, f: impl FnMut(&T) -> S) -> [S; N] {
unsafe {
self.iter()
.map(f)
.collect_vec() .try_into()
.unwrap_unchecked()
}
}
}
impl<T> Kind1To1 for Box<[T]> {
type Constructor<S> = Box<[S]>;
}
impl<T> Functor<T> for Box<[T]> {
fn fmap<S>(self, f: impl FnMut(T) -> S) -> Box<[S]> {
Vec::from(self).fmap(f).into_boxed_slice()
}
}
impl<T> FunctorRef<T> for Box<[T]> {
fn fmap_ref<S>(&self, f: impl FnMut(&T) -> S) -> Box<[S]> {
self.iter().map(f).collect_vec().into_boxed_slice()
}
}