use crate::types::csr_matrix::CsrMatrix;
use alloc::vec;
use alloc::vec::Vec;
use deep_causality_haft::{Applicative, CoMonad, Foldable, Functor, HKT, Pure};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct CsrMatrixWitness;
impl HKT for CsrMatrixWitness {
type Type<T> = CsrMatrix<T>;
}
impl Functor<CsrMatrixWitness> for CsrMatrixWitness {
fn fmap<A, B, Func>(m_a: CsrMatrix<A>, f: Func) -> CsrMatrix<B>
where
Func: FnMut(A) -> B,
{
let (ri, ci, values, shape) = m_a.into_parts();
CsrMatrix::from_raw_parts(ri, ci, values.into_iter().map(f).collect(), shape)
}
}
impl Foldable<CsrMatrixWitness> for CsrMatrixWitness {
fn fold<A, B, Func>(fa: CsrMatrix<A>, init: B, f: Func) -> B
where
Func: FnMut(B, A) -> B,
{
let (_, _, values, _) = fa.into_parts();
values.into_iter().fold(init, f)
}
}
impl Pure<CsrMatrixWitness> for CsrMatrixWitness {
fn pure<T>(value: T) -> CsrMatrix<T> {
CsrMatrix::from_raw_parts(vec![0, 1], vec![0], vec![value], (1, 1))
}
}
impl Applicative<CsrMatrixWitness> for CsrMatrixWitness {
fn apply<A, B, Func>(ff: CsrMatrix<Func>, fa: CsrMatrix<A>) -> CsrMatrix<B>
where
A: Clone,
Func: FnMut(A) -> B,
{
let (f_ri, f_ci, mut fns, f_shape) = ff.into_parts();
let (ri, ci, values, shape) = fa.into_parts();
match (fns.len(), values.len()) {
(1, _) => {
let g = &mut fns[0];
let out: Vec<B> = values.into_iter().map(g).collect();
CsrMatrix::from_raw_parts(ri, ci, out, shape)
}
(_, 1) => {
let a = values.into_iter().next().expect("length checked as one");
let out: Vec<B> = fns.iter_mut().map(|g| g(a.clone())).collect();
CsrMatrix::from_raw_parts(f_ri, f_ci, out, f_shape)
}
_ => {
let out: Vec<B> = fns.iter_mut().zip(values).map(|(g, a)| g(a)).collect();
let kept = out.len();
let ri = ri.into_iter().map(|p| p.min(kept)).collect();
CsrMatrix::from_raw_parts(ri, ci.into_iter().take(kept).collect(), out, shape)
}
}
}
}
impl CoMonad<CsrMatrixWitness> for CsrMatrixWitness {
fn extract<A>(fa: &CsrMatrix<A>) -> A
where
A: Clone,
{
fa.values()
.first()
.cloned()
.expect("Comonad::extract cannot be called on a CsrMatrix that stores nothing")
}
fn extend<A, B, Func>(fa: &CsrMatrix<A>, mut f: Func) -> CsrMatrix<B>
where
A: Clone,
Func: FnMut(&CsrMatrix<A>) -> B,
{
let n = fa.values().len();
let mut out = Vec::with_capacity(n);
for k in 0..n {
let rotated: Vec<A> = (0..n).map(|i| fa.values()[(i + k) % n].clone()).collect();
let view = CsrMatrix::from_raw_parts(
fa.row_indices().clone(),
fa.col_indices().clone(),
rotated,
fa.shape(),
);
out.push(f(&view));
}
CsrMatrix::from_raw_parts(
fa.row_indices().clone(),
fa.col_indices().clone(),
out,
fa.shape(),
)
}
}