concision_traits/ops/
apply.rs

1/*
2    appellation: apply <module>
3    authors: @FL03
4*/
5
6/// [`Apply`] is a composable binary operator generally used to apply some object or function
7/// onto the caller to produce some output.
8pub trait Apply<Rhs> {
9    type Output;
10
11    fn apply(&self, rhs: Rhs) -> Self::Output;
12}
13/// The [`ApplyOnce`] trait consumes the container and applies the given function to every
14/// element before returning a new container with the results.
15pub trait ApplyOnce<Rhs> {
16    type Output;
17
18    fn apply_once(self, rhs: Rhs) -> Self::Output;
19}
20/// [`ApplyMut`] provides an interface for mutable containers that can apply a function onto
21/// their elements, modifying them in place.
22pub trait ApplyMut<Rhs> {
23    fn apply_mut(&mut self, rhs: Rhs);
24}
25
26/*
27 ************* Implementations *************
28*/
29use ndarray::{Array, ArrayBase, Data, DataMut, Dimension};
30
31impl<U, V, F> ApplyOnce<F> for Option<U>
32where
33    F: FnOnce(U) -> V,
34{
35    type Output = Option<V>;
36
37    fn apply_once(self, f: F) -> Self::Output {
38        self.map(f)
39    }
40}
41
42impl<A, S, D, F> ApplyMut<F> for ArrayBase<S, D, A>
43where
44    A: Clone,
45    D: Dimension,
46    S: DataMut<Elem = A>,
47    F: FnMut(A) -> A,
48{
49    fn apply_mut(&mut self, f: F) {
50        self.mapv_inplace(f)
51    }
52}
53
54impl<A, B, S, D, F> Apply<F> for ArrayBase<S, D, A>
55where
56    A: Clone,
57    D: Dimension,
58    S: Data<Elem = A>,
59    F: Fn(A) -> B,
60{
61    type Output = Array<B, D>;
62
63    fn apply(&self, f: F) -> Self::Output {
64        self.mapv(f)
65    }
66}