use crate::types::dense_matrix::DenseMatrix;
use deep_causality_haft::{Applicative, CoMonad, Foldable, Functor, HKT, Pure};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct DenseMatrixWitness;
impl HKT for DenseMatrixWitness {
type Type<T> = DenseMatrix<T>;
}
impl Functor<DenseMatrixWitness> for DenseMatrixWitness {
fn fmap<A, B, Func>(m_a: DenseMatrix<A>, f: Func) -> DenseMatrix<B>
where
Func: FnMut(A) -> B,
{
let (r, c) = (m_a.rows_pub(), m_a.cols_pub());
let mapped: alloc::vec::Vec<B> = m_a.into_data().into_iter().map(f).collect();
DenseMatrix::from_vec(mapped, r, c).expect("fmap preserves the element count")
}
}
impl Foldable<DenseMatrixWitness> for DenseMatrixWitness {
fn fold<A, B, Func>(fa: DenseMatrix<A>, init: B, f: Func) -> B
where
Func: FnMut(B, A) -> B,
{
fa.into_data().into_iter().fold(init, f)
}
}
impl Pure<DenseMatrixWitness> for DenseMatrixWitness {
fn pure<T>(value: T) -> DenseMatrix<T> {
DenseMatrix::from_vec(alloc::vec![value], 1, 1).expect("1x1 holds exactly one value")
}
}
impl Applicative<DenseMatrixWitness> for DenseMatrixWitness {
fn apply<A, B, Func>(ff: DenseMatrix<Func>, fa: DenseMatrix<A>) -> DenseMatrix<B>
where
A: Clone,
Func: FnMut(A) -> B,
{
let (fr, fc) = (ff.rows_pub(), ff.cols_pub());
let (ar, ac) = (fa.rows_pub(), fa.cols_pub());
let mut fns = ff.into_data();
let vals = fa.into_data();
let (r, c, out): (usize, usize, alloc::vec::Vec<B>) = match (fns.len(), vals.len()) {
(1, _) => {
let g = &mut fns[0];
(ar, ac, vals.into_iter().map(g).collect())
}
(_, 1) => {
let a = vals.into_iter().next().expect("length checked as one");
(fr, fc, fns.iter_mut().map(|g| g(a.clone())).collect())
}
_ => (
ar,
ac,
fns.iter_mut().zip(vals).map(|(g, a)| g(a)).collect(),
),
};
DenseMatrix::from_vec(out, r, c).expect("apply preserves the element count")
}
}
impl CoMonad<DenseMatrixWitness> for DenseMatrixWitness {
fn extract<A>(fa: &DenseMatrix<A>) -> A
where
A: Clone,
{
fa.as_slice()
.first()
.cloned()
.expect("a comonad has no counit for an empty container")
}
fn extend<A, B, Func>(fa: &DenseMatrix<A>, mut f: Func) -> DenseMatrix<B>
where
A: Clone,
Func: FnMut(&DenseMatrix<A>) -> B,
{
let (r, c) = (fa.rows_pub(), fa.cols_pub());
let mut out = alloc::vec::Vec::with_capacity(r * c);
for i in 0..r {
for j in 0..c {
let view = shifted_view(fa, i, j);
out.push(f(&view));
}
}
DenseMatrix::from_vec(out, r, c).expect("extend preserves the shape")
}
}
fn shifted_view<A: Clone>(fa: &DenseMatrix<A>, row: usize, col: usize) -> DenseMatrix<A> {
let (r, c) = (fa.rows_pub(), fa.cols_pub());
let mut out = alloc::vec::Vec::with_capacity(r * c);
for i in 0..r {
for j in 0..c {
let si = (i + row) % r;
let sj = (j + col) % c;
out.push(fa.as_slice()[si * c + sj].clone());
}
}
DenseMatrix::from_vec(out, r, c).expect("a rotation preserves the element count")
}