From f5be71d4d372cf0c39f0fa44b8a5ba0285561168 Mon Sep 17 00:00:00 2001 From: Gergo ERDI Date: Sat, 12 Oct 2024 20:20:35 +0800 Subject: [PATCH] Add `Distributive` and `Representable` instances to `Vec n` --- ...17_43_16+08_00_distributive_representative_vec | 1 + clash-prelude/clash-prelude.cabal | 4 +++- clash-prelude/src/Clash/Sized/Vector.hs | 15 +++++++++++++++ 3 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 changelog/2024-11-02T17_43_16+08_00_distributive_representative_vec diff --git a/changelog/2024-11-02T17_43_16+08_00_distributive_representative_vec b/changelog/2024-11-02T17_43_16+08_00_distributive_representative_vec new file mode 100644 index 0000000000..80c541ba62 --- /dev/null +++ b/changelog/2024-11-02T17_43_16+08_00_distributive_representative_vec @@ -0,0 +1 @@ +ADDED: `Distributive` and `Representable` instances for `Vec` diff --git a/clash-prelude/clash-prelude.cabal b/clash-prelude/clash-prelude.cabal index 47bb2d26db..c4679a9204 100644 --- a/clash-prelude/clash-prelude.cabal +++ b/clash-prelude/clash-prelude.cabal @@ -317,7 +317,8 @@ Library TypeFamilies UndecidableInstances - Build-depends: array >= 0.5.1.0 && < 0.6, + Build-depends: adjunctions >= 4.0 && < 5.0, + array >= 0.5.1.0 && < 0.6, arrows >= 0.4 && < 0.5, base >= 4.11 && < 5, binary >= 0.8.5 && < 0.11, @@ -327,6 +328,7 @@ Library data-binary-ieee754 >= 0.4.4 && < 0.6, data-default-class >= 0.1.2 && < 0.2, deepseq >= 1.4.1.0 && < 1.6, + distributive >= 0.1 && < 1.0, extra >= 1.6.17 && < 1.8, ghc-prim >= 0.5.1.0 && < 0.12, ghc-typelits-extra >= 0.4 && < 0.5, diff --git a/clash-prelude/src/Clash/Sized/Vector.hs b/clash-prelude/src/Clash/Sized/Vector.hs index 72cd2d5179..815b9d7d44 100644 --- a/clash-prelude/src/Clash/Sized/Vector.hs +++ b/clash-prelude/src/Clash/Sized/Vector.hs @@ -108,6 +108,8 @@ import Data.Constraint.Nat (leZero) import Data.Data (Data (..), Constr, DataType, Fixity (..), Typeable, mkConstr, mkDataType) import Data.Either (isLeft) +import Data.Distributive +import Data.Functor.Rep #if MIN_VERSION_base(4,18,0) import qualified Data.Foldable1 as F1 #endif @@ -2776,3 +2778,16 @@ type instance Lens.Index (Vec n a) = Index n type instance Lens.IxValue (Vec n a) = a instance KnownNat n => Lens.Ixed (Vec n a) where ix i f xs = replace_int xs (fromEnum i) <$> f (index_int xs (fromEnum i)) + +instance KnownNat n => Distributive (Vec n) where + distribute fxs = tabulate $ \i -> fmap (!! i) fxs + {-# INLINE distribute #-} + +instance KnownNat n => Representable (Vec n) where + type Rep (Vec n) = Index n + + tabulate f = map f indicesI + {-# INLINE tabulate #-} + + index = (!!) + {-# INLINE index #-}