deep_causality_haft/extensions/
func_fold_vec_deque_ext.rs

1/*
2 * SPDX-License-Identifier: MIT
3 * Copyright (c) "2025" . The DeepCausality Authors and Contributors. All Rights Reserved.
4 */
5
6use crate::{Foldable, Functor, HKT};
7use alloc::collections::VecDeque;
8
9/// `VecDequeWitness` is a zero-sized type that acts as a Higher-Kinded Type (HKT) witness
10/// for the `VecDeque<T>` type constructor. It allows `VecDeque` to be used with generic
11/// functional programming traits like `Functor` and `Foldable`.
12///
13/// By implementing `HKT` for `VecDequeWitness`, we can write generic functions that operate
14/// on any type that has the "shape" of `VecDeque`, without knowing the inner type `T`.
15pub struct VecDequeWitness;
16
17impl HKT for VecDequeWitness {
18    /// Specifies that `VecDequeWitness` represents the `VecDeque<T>` type constructor.
19    type Type<T> = VecDeque<T>;
20}
21
22// Implementation of Functor for VecDequeWitness
23impl Functor<VecDequeWitness> for VecDequeWitness {
24    /// Implements the `fmap` operation for `VecDeque<T>`.
25    ///
26    /// Applies the function `f` to each element in the vector deque, producing a new vector deque.
27    ///
28    /// # Arguments
29    ///
30    /// *   `m_a`: The `VecDeque` to map over.
31    /// *   `f`: The function to apply to each element.
32    ///
33    /// # Returns
34    ///
35    /// A new `VecDeque` with the function applied to each of its elements.
36    fn fmap<A, B, Func>(
37        m_a: <VecDequeWitness as HKT>::Type<A>,
38        f: Func,
39    ) -> <VecDequeWitness as HKT>::Type<B>
40    where
41        Func: FnMut(A) -> B,
42    {
43        m_a.into_iter().map(f).collect()
44    }
45}
46
47// Implementation of Foldable for VecDequeWitness
48impl Foldable<VecDequeWitness> for VecDequeWitness {
49    /// Folds (reduces) a `VecDeque` into a single value.
50    ///
51    /// Applies the function `f` cumulatively to the elements of the vector deque,
52    /// starting with an initial accumulator value.
53    ///
54    /// # Arguments
55    ///
56    /// *   `fa`: The `VecDeque` to fold.
57    /// *   `init`: The initial accumulator value.
58    /// *   `f`: The folding function.
59    ///
60    /// # Returns
61    ///
62    /// The accumulated result.
63    fn fold<A, B, Func>(fa: VecDeque<A>, init: B, f: Func) -> B
64    where
65        Func: FnMut(B, A) -> B,
66    {
67        fa.into_iter().fold(init, f)
68    }
69}