concision_traits/ops/
map.rs

1/*
2    Appellation: map <module>
3    Created At: 2026.01.06:13:50:37
4    Contrib: @FL03
5*/
6/// [`MapInto`] defines an interface for containers that can consume themselves to apply a given
7/// function onto each of their elements.
8pub trait MapInto<F, U>
9where
10    F: FnOnce(Self::Elem) -> U,
11{
12    type Cont<_T>;
13    type Elem;
14
15    fn mapi(self, f: F) -> Self::Cont<U>;
16}
17
18/// [`MapTo`] establishes an interface for containers capable of applying a given function onto
19/// each of their elements, by reference.
20pub trait MapTo<F, U>
21where
22    F: FnOnce(Self::Elem) -> U,
23{
24    type Cont<_T>;
25    type Elem;
26
27    fn mapt(&self, f: F) -> Self::Cont<U>;
28}
29
30/*
31 ************* Implementations *************
32*/
33use ndarray::{Array, ArrayBase, Data, Dimension};
34
35impl<U, V, F> MapInto<F, V> for Option<U>
36where
37    F: FnOnce(U) -> V,
38{
39    type Cont<W> = Option<W>;
40    type Elem = U;
41
42    fn mapi(self, f: F) -> Self::Cont<V> {
43        self.map(f)
44    }
45}
46
47impl<'a, U, V, F> MapTo<F, V> for Option<&'a U>
48where
49    for<'b> F: FnOnce(&'b U) -> V,
50{
51    type Cont<W> = Option<W>;
52    type Elem = &'a U;
53
54    fn mapt(&self, f: F) -> Self::Cont<V> {
55        self.as_ref().map(|a| f(a))
56    }
57}
58
59impl<A, B, S, D, F> MapInto<F, B> for ArrayBase<S, D, A>
60where
61    A: Clone,
62    D: Dimension,
63    S: Data<Elem = A>,
64    F: Fn(A) -> B,
65{
66    type Cont<V> = Array<V, D>;
67    type Elem = A;
68
69    fn mapi(self, f: F) -> Self::Cont<B> {
70        self.mapv(f)
71    }
72}
73
74impl<A, B, S, D, F> MapInto<F, B> for &ArrayBase<S, D, A>
75where
76    A: Clone,
77    D: Dimension,
78    S: Data<Elem = A>,
79    F: Fn(A) -> B,
80{
81    type Cont<V> = Array<V, D>;
82    type Elem = A;
83
84    fn mapi(self, f: F) -> Self::Cont<B> {
85        self.mapv(f)
86    }
87}
88
89impl<A, B, S, D, F> MapTo<F, B> for ArrayBase<S, D, A>
90where
91    A: Clone,
92    D: Dimension,
93    S: Data<Elem = A>,
94    F: Fn(A) -> B,
95{
96    type Cont<V> = Array<V, D>;
97    type Elem = A;
98
99    fn mapt(&self, f: F) -> Self::Cont<B> {
100        self.mapv(f)
101    }
102}