gongju 0.1.0.0 → 0.1.2.0
raw patch · 7 files changed
+1063/−10 lines, 7 filesdep +containersdep +nonempty-containersdep +witherablePVP ok
version bump matches the API change (PVP)
Dependencies added: containers, nonempty-containers, witherable
API changes (from Hackage documentation)
+ Gongju.Diagonal: Zippy :: f a -> Zippy (f :: k -> Type) (a :: k)
+ Gongju.Diagonal: [unZippy] :: Zippy (f :: k -> Type) (a :: k) -> f a
+ Gongju.Diagonal: class HomArity (n :: Peano) a b r fnB fnA | n fnB a b -> r fnA, n fnA a b -> r fnB, n a b r -> fnB fnA
+ Gongju.Diagonal: class HomArityM (n :: Peano) (m :: Type -> Type) a b r fnB fnA | n m fnB a b -> r fnA, n m a b r -> fnB fnA
+ Gongju.Diagonal: class ZipArity (n :: Peano) (f :: Type -> Type) fn zipFn | n f fn -> zipFn, n zipFn -> f fn
+ Gongju.Diagonal: class Functor f => ZipContainer (f :: Type -> Type)
+ Gongju.Diagonal: diagMN :: forall (n :: Nat) m a b r fnB fnA. (Applicative m, HomArityM (ToPeano n) m a b r fnB fnA) => (a -> m b) -> fnB -> a -> m r
+ Gongju.Diagonal: diagMPeano :: HomArityM n m a b r fnB fnA => (a -> m b) -> m fnB -> a -> m r
+ Gongju.Diagonal: diagN :: forall (n :: Nat) a b r fnB fnA. HomArity (ToPeano n) a b r fnB fnA => (a -> b) -> fnB -> a -> r
+ Gongju.Diagonal: diagPeano :: HomArity n a b r fnB fnA => (a -> b) -> fnB -> a -> r
+ Gongju.Diagonal: instance GHC.Internal.Base.Functor f => GHC.Internal.Base.Functor (Gongju.Diagonal.Zippy f)
+ Gongju.Diagonal: instance GHC.Internal.Data.Foldable.Foldable f => GHC.Internal.Data.Foldable.Foldable (Gongju.Diagonal.Zippy f)
+ Gongju.Diagonal: instance Gongju.Diagonal.HomArity 'Gongju.Peano.Z a b r r r
+ Gongju.Diagonal: instance Gongju.Diagonal.HomArity n a b r fnB fnA => Gongju.Diagonal.HomArity ('Gongju.Peano.S n) a b r (b -> fnB) (a -> fnA)
+ Gongju.Diagonal: instance Gongju.Diagonal.HomArityM 'Gongju.Peano.Z m a b r r (m r)
+ Gongju.Diagonal: instance Gongju.Diagonal.HomArityM n m a b r fnB fnA => Gongju.Diagonal.HomArityM ('Gongju.Peano.S n) m a b r (b -> fnB) (a -> fnA)
+ Gongju.Diagonal: instance Gongju.Diagonal.ZipArity 'Gongju.Peano.Z f r (f r)
+ Gongju.Diagonal: instance Gongju.Diagonal.ZipArity n f fn zipFn => Gongju.Diagonal.ZipArity ('Gongju.Peano.S n) f (a -> fn) (f a -> zipFn)
+ Gongju.Diagonal: instance Gongju.Diagonal.ZipContainer Data.Sequence.Internal.Seq
+ Gongju.Diagonal: instance Gongju.Diagonal.ZipContainer GHC.Internal.Base.NonEmpty
+ Gongju.Diagonal: instance Gongju.Diagonal.ZipContainer GHC.Internal.Functor.ZipList.ZipList
+ Gongju.Diagonal: instance Gongju.Diagonal.ZipContainer []
+ Gongju.Diagonal: instance Gongju.Diagonal.ZipContainer f => GHC.Internal.Base.Applicative (Gongju.Diagonal.Zippy f)
+ Gongju.Diagonal: instance forall k (f :: k -> *) (a :: k). GHC.Internal.Classes.Eq (f a) => GHC.Internal.Classes.Eq (Gongju.Diagonal.Zippy f a)
+ Gongju.Diagonal: instance forall k (f :: k -> *) (a :: k). GHC.Internal.Classes.Ord (f a) => GHC.Internal.Classes.Ord (Gongju.Diagonal.Zippy f a)
+ Gongju.Diagonal: instance forall k (f :: k -> *) (a :: k). GHC.Internal.Show.Show (f a) => GHC.Internal.Show.Show (Gongju.Diagonal.Zippy f a)
+ Gongju.Diagonal: newtype Zippy (f :: k -> Type) (a :: k)
+ Gongju.Diagonal: onMN :: forall (n :: Nat) m a b r fnB fnA. (Applicative m, HomArityM (ToPeano n) m a b r fnB fnA) => (a -> m b) -> fnB -> fnA
+ Gongju.Diagonal: onMPeano :: HomArityM n m a b r fnB fnA => (a -> m b) -> m fnB -> fnA
+ Gongju.Diagonal: onN :: forall (n :: Nat) a b r fnB fnA. HomArity (ToPeano n) a b r fnB fnA => (a -> b) -> fnB -> fnA
+ Gongju.Diagonal: onPeano :: HomArity n a b r fnB fnA => (a -> b) -> fnB -> fnA
+ Gongju.Diagonal: zipAp :: ZipContainer f => f (a -> b) -> f a -> f b
+ Gongju.Diagonal: zipPeano :: ZipArity n f fn zipFn => f fn -> zipFn
+ Gongju.Diagonal: zipPure :: ZipContainer f => a -> f a
+ Gongju.Diagonal: zipWithN :: forall (n :: Nat) (f :: Type -> Type) fn zipFn. (ZipContainer f, ZipArity (ToPeano n) f fn zipFn) => fn -> zipFn
+ Gongju.Evacuate: -- collection.
+ Gongju.Evacuate: -- | Canonical evacuable container type representing the unconstrained
+ Gongju.Evacuate: class Filterable EvacCarrier c => Evacuable (c :: Type -> Type) a where {
+ Gongju.Evacuate: fromEvac :: Evacuable c a => EvacCarrier c a -> Maybe (c a)
+ Gongju.Evacuate: groupEvac :: (Foldable f, Ord k, Evacuable c a, EvacCarrier c ~ [], Semigroup (c a)) => f (k, a) -> Map k (c a)
+ Gongju.Evacuate: groupEvacMany :: (Foldable f, Ord k, Evacuable c1 a, Evacuable c2 a, EvacCarrier c1 ~ EvacCarrier c2, Semigroup (c2 a)) => f (k, c1 a) -> Map k (c2 a)
+ Gongju.Evacuate: insertEvac :: (Ord k, Evacuable c1 a, Evacuable c2 a, EvacCarrier c1 ~ EvacCarrier c2, Semigroup (c2 a)) => k -> c1 a -> Map k (c2 a) -> Map k (c2 a)
+ Gongju.Evacuate: instance GHC.Internal.Classes.Ord a => Gongju.Evacuate.Evacuable Data.Set.Internal.Set a
+ Gongju.Evacuate: instance GHC.Internal.Classes.Ord a => Gongju.Evacuate.Evacuable Data.Set.NonEmpty.Internal.NESet a
+ Gongju.Evacuate: instance Gongju.Evacuate.Evacuable Data.Sequence.Internal.Seq a
+ Gongju.Evacuate: instance Gongju.Evacuate.Evacuable Data.Sequence.NonEmpty.Internal.NESeq a
+ Gongju.Evacuate: instance Gongju.Evacuate.Evacuable GHC.Internal.Base.NonEmpty a
+ Gongju.Evacuate: instance Gongju.Evacuate.Evacuable GHC.Internal.Maybe.Maybe a
+ Gongju.Evacuate: instance Gongju.Evacuate.Evacuable [] a
+ Gongju.Evacuate: mapMaybeEvac :: (Evacuable c1 a, Evacuable c2 b, EvacCarrier c1 ~ EvacCarrier c2) => (a -> Maybe b) -> c1 a -> Maybe (c2 b)
+ Gongju.Evacuate: sift :: (Evacuable c1 a, Evacuable c2 a, EvacCarrier c1 ~ EvacCarrier c2) => (a -> Bool) -> c1 a -> Maybe (c2 a)
+ Gongju.Evacuate: toEvac :: Evacuable c a => c a -> EvacCarrier c a
+ Gongju.Evacuate: type EvacCarrier (c :: Type -> Type) :: Type -> Type;
+ Gongju.Evacuate: witherEvac :: (Applicative m, Evacuable c1 a, Evacuable c2 b, EvacCarrier c1 ~ EvacCarrier c2, Witherable (EvacCarrier c1)) => (a -> m (Maybe b)) -> c1 a -> m (Maybe (c2 b))
+ Gongju.Evacuate: }
+ Gongju.Spine: LayerMonad :: LayerTag
+ Gongju.Spine: LayerTarget :: LayerTag
+ Gongju.Spine: LayerTraversable :: LayerTag
+ Gongju.Spine: class SpineBind (d :: Peano) (tag :: LayerTag) (m :: Type -> Type) spine a b out | d tag m spine b -> out, d tag m spine -> a
+ Gongju.Spine: class SpineWither (d :: Peano) (tag :: LayerTag) (m :: Type -> Type) spine a b out | d tag m spine b -> out, d tag m spine -> a
+ Gongju.Spine: data LayerTag
+ Gongju.Spine: forMN :: forall (d :: Nat) m spine a b out. (Monad m, SpineBind (ToPeano d) (ClassifyLayer (ToPeano d) m spine) m spine a b out) => (a -> m b) -> spine -> m out
+ Gongju.Spine: instance (GHC.Internal.Data.Traversable.Traversable t, nextTag GHC.Internal.Types.~ Gongju.Spine.ClassifyLayer d m inner, Gongju.Spine.SpineBind d nextTag m inner a b out) => Gongju.Spine.SpineBind ('Gongju.Peano.S d) 'Gongju.Spine.LayerTraversable m (t inner) a b (t out)
+ Gongju.Spine: instance (GHC.Internal.Data.Traversable.Traversable t, nextTag GHC.Internal.Types.~ Gongju.Spine.ClassifyLayer d m inner, Gongju.Spine.SpineWither d nextTag m inner a b out) => Gongju.Spine.SpineWither ('Gongju.Peano.S d) 'Gongju.Spine.LayerTraversable m (t inner) a b (t out)
+ Gongju.Spine: instance (nextTag GHC.Internal.Types.~ Gongju.Spine.ClassifyLayer d m inner, Gongju.Spine.SpineBind d nextTag m inner a b out) => Gongju.Spine.SpineBind ('Gongju.Peano.S d) 'Gongju.Spine.LayerMonad m (m inner) a b out
+ Gongju.Spine: instance (nextTag GHC.Internal.Types.~ Gongju.Spine.ClassifyLayer d m inner, Gongju.Spine.SpineWither d nextTag m inner a b out) => Gongju.Spine.SpineWither ('Gongju.Peano.S d) 'Gongju.Spine.LayerMonad m (m inner) a b out
+ Gongju.Spine: instance Gongju.Spine.SpineBind 'Gongju.Peano.Z 'Gongju.Spine.LayerTarget m a a b b
+ Gongju.Spine: instance Witherable.Witherable w => Gongju.Spine.SpineWither 'Gongju.Peano.Z 'Gongju.Spine.LayerTarget m (w a) a b (w b)
+ Gongju.Spine: spineBindPeano :: SpineBind d tag m spine a b out => spine -> (a -> m b) -> m out
+ Gongju.Spine: spineFor :: forall (d :: Nat) m spine a b out. (Monad m, SpineBind (ToPeano d) (ClassifyLayer (ToPeano d) m spine) m spine a b out) => spine -> (a -> m b) -> m out
+ Gongju.Spine: spineWither :: forall (d :: Nat) m spine a b out. (Monad m, SpineWither (ToPeano d) (ClassifyLayer (ToPeano d) m spine) m spine a b out) => spine -> (a -> m (Maybe b)) -> m out
+ Gongju.Spine: spineWitherPeano :: SpineWither d tag m spine a b out => spine -> (a -> m (Maybe b)) -> m out
+ Gongju.Spine: type family ClassifyLayer (d :: Peano) (m :: Type -> Type) spine :: LayerTag
+ Gongju.Spine: witherMN :: forall (d :: Nat) m spine a b out. (Monad m, SpineWither (ToPeano d) (ClassifyLayer (ToPeano d) m spine) m spine a b out) => (a -> m (Maybe b)) -> spine -> m out
+ Gongju.Tuple: class TupleCurry (n :: Peano) tup r fn | tup r -> n fn, n fn -> tup r
+ Gongju.Tuple: class TupleHom tupA tupB a b | tupA -> a, tupB -> b, tupA b -> tupB, tupB a -> tupA
+ Gongju.Tuple: curryFlat :: TupleCurry n tup r fn => (tup -> r) -> fn
+ Gongju.Tuple: instance Gongju.Tuple.TupleCurry ('Gongju.Peano.S ('Gongju.Peano.S 'Gongju.Peano.Z)) (a, b) r (a -> b -> r)
+ Gongju.Tuple: instance Gongju.Tuple.TupleCurry ('Gongju.Peano.S ('Gongju.Peano.S ('Gongju.Peano.S 'Gongju.Peano.Z))) (a, b, c) r (a -> b -> c -> r)
+ Gongju.Tuple: instance Gongju.Tuple.TupleCurry ('Gongju.Peano.S ('Gongju.Peano.S ('Gongju.Peano.S ('Gongju.Peano.S 'Gongju.Peano.Z)))) (a, b, c, d) r (a -> b -> c -> d -> r)
+ Gongju.Tuple: instance Gongju.Tuple.TupleCurry ('Gongju.Peano.S ('Gongju.Peano.S ('Gongju.Peano.S ('Gongju.Peano.S ('Gongju.Peano.S 'Gongju.Peano.Z))))) (a, b, c, d, e) r (a -> b -> c -> d -> e -> r)
+ Gongju.Tuple: instance Gongju.Tuple.TupleHom (a, a) (b, b) a b
+ Gongju.Tuple: instance Gongju.Tuple.TupleHom (a, a, a) (b, b, b) a b
+ Gongju.Tuple: instance Gongju.Tuple.TupleHom (a, a, a, a) (b, b, b, b) a b
+ Gongju.Tuple: instance Gongju.Tuple.TupleHom (a, a, a, a, a) (b, b, b, b, b) a b
+ Gongju.Tuple: mapTupleHom :: TupleHom tupA tupB a b => (a -> b) -> tupA -> tupB
+ Gongju.Tuple: traverseTupleHom :: (TupleHom tupA tupB a b, Applicative m) => (a -> m b) -> tupA -> m tupB
+ Gongju.Tuple: uncurryFlat :: TupleCurry n tup r fn => fn -> tup -> r
Files
- gongju.cabal +21/−8
- src/Gongju.hs +84/−0
- src/Gongju/Diagonal.hs +284/−0
- src/Gongju/Evacuate.hs +248/−0
- src/Gongju/Spine.hs +221/−0
- src/Gongju/Tuple.hs +167/−0
- test/Main.hs +38/−2
gongju.cabal view
@@ -1,6 +1,6 @@ cabal-version: 3.0 name: gongju-version: 0.1.0.0+version: 0.1.2.0 synopsis: Pure type-level utility functions, arity composition, and curried combinators description: Gongju (공구 / 工具, tools/implement) provides inductive Peano type-level@@ -34,6 +34,7 @@ common commons default-language: Haskell2010+ default-extensions: ImportQualifiedPost ghc-options: -Wall -Wcompat@@ -43,28 +44,36 @@ import: commons hs-source-dirs: src exposed-modules:+ Gongju+ Gongju.Adjunction+ Gongju.Comonad Gongju.Core Gongju.Peano Gongju.Composition- Gongju.Positional- Gongju.Permute+ Gongju.Contravariant+ Gongju.Diagonal+ Gongju.Evacuate Gongju.Indexed- Gongju.Comonad- Gongju.Adjunction Gongju.Kan- Gongju.Profunctor- Gongju.Contravariant Gongju.Monad+ Gongju.Permute+ Gongju.Positional+ Gongju.Profunctor+ Gongju.Spine+ Gongju.Tuple build-depends: base >= 4.20 && < 5 , adjunctions >= 4.4 && < 5 , comonad >= 5 && < 6+ , containers >= 0.6 && < 1+ , contravariant >= 1.5 && < 2 , distributive >= 0.6 && < 1 , indexed >= 0.1 && < 1 , indexed-profunctors >= 0.1 && < 1 , kan-extensions >= 5.2 && < 6+ , nonempty-containers >= 0.3 && < 1 , profunctors >= 5.6 && < 6- , contravariant >= 1.5 && < 2+ , witherable >= 0.4 && < 1 test-suite gongju-test import: commons@@ -72,6 +81,10 @@ hs-source-dirs: test main-is: Main.hs other-modules: CoreInspection+ ghc-options:+ -threaded+ -rtsopts+ "-with-rtsopts=-N" build-depends: base >= 4.20 && < 5 , adjunctions >= 4.4 && < 5
+ src/Gongju.hs view
@@ -0,0 +1,84 @@+-- | Module: Gongju+-- Description: Top-level prelude and unified combinator re-export for the gongju toolmaker library+--+-- Gongju (공구 / 工具, tools/implement) provides inductive Peano type-level+-- utility functions in pure Haskell, replacing Template Haskell arity splices+-- and finite tuple generics with zero-overhead typeclass induction, bidirectional+-- functional dependencies, and 'GHC.TypeNats.Nat' wrappers.+--+-- = Architectural Context+--+-- Per Note [Gongju Combinator Taxonomy] [ref:note-gongju-combinators], 'Gongju'+-- collects all specialized combinator categories into a single import surface:+--+-- * "Gongju.Core": Fundamental Peano arithmetic, 'ToPeano' type families, and induction.+-- * "Gongju.Diagonal": Homogeneous arity distribution ('onN', 'diagN') and variadic zipping ('zipWithN').+-- * "Gongju.Spine": Arbitrary-depth interleaved Monad/Traversable spine binding ('spineFor', 'spineWither').+-- * "Gongju.Evacuate": Evacuability polymorphism bridging non-empty and evacuable collections ('sift', 'insertEvac').+-- * "Gongju.Tuple": Flat GHC tuple currying isomorphisms ('curryFlat', 'uncurryFlat') and mapping ('mapTupleHom').+-- * "Gongju.Composition": Multi-arity function composition and pipeline wiring.+-- * "Gongju.Permute": Curried argument permutation and transposition.+-- * "Gongju.Positional": Positional indexing and targeted argument application.+--+-- == Invariants & Guarantees+--+-- 1. __Zero Allocation Overhead:__ All exposed combinators expand to primitive+-- unboxed functions or GHC Core case matches.+-- 2. __Purity & Totality:__ Every function exported through this prelude is total.+-- 3. __Comment Density:__ Fully documented with Haddock examples satisfying Gate 5.+--+-- = Worked Example+--+-- >>> onN @2 (* 10) (,) 3 4+-- (30, 40)+--+-- >>> sift (> 1) (1 :| [2, 3]) :: Maybe (NonEmpty Int)+-- Just (2 :| [3])+module Gongju+ ( -- * 1. Core Peano & Natural Number Infrastructure+ module Gongju.Core+ , module Gongju.Peano++ -- * 2. Arity Distribution & Diagonalization+ , module Gongju.Diagonal++ -- * 3. Deep Spine Traversal & Contraction+ , module Gongju.Spine++ -- * 4. Evacuability Polymorphism+ , module Gongju.Evacuate++ -- * 5. Tuple Currying & Homogeneous Distribution+ , module Gongju.Tuple++ -- * 6. High-Arity Composition & Combinators+ , module Gongju.Composition+ , module Gongju.Permute+ , module Gongju.Positional++ -- * 7. Categorical Functor & Profunctor Infrastructure+ , module Gongju.Adjunction+ , module Gongju.Comonad+ , module Gongju.Contravariant+ , module Gongju.Indexed+ , module Gongju.Kan+ , module Gongju.Monad+ , module Gongju.Profunctor+ ) where++import Gongju.Adjunction+import Gongju.Comonad+import Gongju.Composition+import Gongju.Contravariant+import Gongju.Core+import Gongju.Diagonal+import Gongju.Evacuate+import Gongju.Indexed+import Gongju.Kan+import Gongju.Monad+import Gongju.Peano+import Gongju.Permute+import Gongju.Positional+import Gongju.Profunctor+import Gongju.Spine+import Gongju.Tuple
+ src/Gongju/Diagonal.hs view
@@ -0,0 +1,284 @@+{-# LANGUAGE AllowAmbiguousTypes #-}+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE FunctionalDependencies #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE PolyKinds #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeApplications #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE UndecidableInstances #-}++-- | Module: Gongju.Diagonal+-- Description: Homogeneous arity distribution, diagonalization, and variadic zipping+--+-- This module implements type-level arity distribution combinators ('onN', 'diagN')+-- and effectful applicative lifting ('onMN', 'diagMN') over @n@ homogeneous arguments,+-- as well as variadic zipping ('zipWithN') for arbitrary zippable containers ('Zippy').+--+-- = Architectural Context+--+-- Per Note [Gongju Combinator Taxonomy] [ref:note-gongju-combinators], distributing+-- unary or effectful functions across multi-argument curried functions or data+-- constructors often leads to bespoke per-arity combinators (@on2@, @on3@, @dup@, @dup3@).+-- 'Gongju.Diagonal' parameterizes this pattern by a type-level Peano number or 'Nat',+-- providing a zero-cost abstraction that collapses along diagonals and lifts Applicative+-- effects outward automatically.+--+-- == Invariants & Guarantees+--+-- 1. __Zero-Cost Inlining:__ All recursive Peano steps are marked with @{-# INLINE #-}@+-- and fully unroll at compile-time under GHC optimization.+-- 2. __Morphism Distribution Law:__ For any unary morphism \(f: A \to B\) and+-- \(g: B \to \dots \to B \to R\):+-- \[+-- \text{onN } f \; g \; x_1 \dots x_n = g \; (f \; x_1) \dots (f \; x_n)+-- \]+-- 3. __Diagonalization Law:__+-- \[+-- \text{diagN } f \; g \; x = g \; (f \; x) \dots (f \; x)+-- \]+--+-- = Worked Examples+--+-- >>> onN @2 (* 10) (,) 3 4+-- (30, 40)+--+-- >>> onN @3 show (,,) 1 2 3+-- ("1", "2", "3")+--+-- >>> diagN @2 (+) 5+-- 10+--+-- >>> diagN @3 (,,) "sky"+-- ("sky", "sky", "sky")+--+-- >>> zipWithN @3 (,,) [1, 2] ['a', 'b'] [True, False]+-- [(1, 'a', True), (2, 'b', False)]+module Gongju.Diagonal+ ( -- * 1. Homogeneous Arity Distribution & Diagonal (`onN`, `diagN`)+ HomArity (..)+ , onN+ , diagN+ -- * 2. Applicative/Monadic Outward Lifting over Arity `n` (`onMN`, `diagMN`)+ , HomArityM (..)+ , onMN+ , diagMN+ -- * 3. Generalised Arity-`n` Zipping (`Zippy`, `ZipArity`, `zipWithN`)+ , ZipContainer (..)+ , Zippy (..)+ , ZipArity (..)+ , zipWithN+ ) where++import Control.Applicative (ZipList (..))+import Data.Kind (Type)+import Data.List.NonEmpty (NonEmpty (..))+import Data.Sequence (Seq)+import Data.Sequence qualified as Seq+import GHC.TypeNats (Nat)++import Gongju.Core (Peano (..), ToPeano)++{- Note [Gongju Combinator Taxonomy]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+[tag:note-gongju-combinators]+Distributing unary or effectful functions across multi-argument curried functions or data+constructors often leads to bespoke per-arity combinators (on2, on3, dup, dup3).+Gongju parameterizes this pattern by a type-level Peano number or Nat, providing a+zero-cost abstraction that collapses along diagonals and lifts Applicative effects outward automatically.+-}++--------------------------------------------------------------------------------+-- 1. Pure Homogeneous Arity Distribution (`onN`) & Diagonal (`diagN`)+--------------------------------------------------------------------------------++-- | Distributes a unary morphism @a -> b@ across @n@ homogeneous arguments of+-- a curried function or data constructor @b -> ... -> b -> r@, and collapses+-- it along the diagonal @a -> r@.+class HomArity (n :: Peano) a b r fnB fnA+ | n fnB a b -> r fnA+ , n fnA a b -> r fnB+ , n a b r -> fnB fnA+ where+ -- | Pre-compose @a -> b@ onto all @n@ arguments of @fnB@.+ onPeano :: (a -> b) -> fnB -> fnA++ -- | Diagonalize @fnB@ by feeding @f x@ into all @n@ argument slots.+ diagPeano :: (a -> b) -> fnB -> (a -> r)++-- | Base case: 0 arguments to distribute.+instance HomArity 'Z a b r r r where+ onPeano _ r = r+ diagPeano _ r _ = r+ {-# INLINE onPeano #-}+ {-# INLINE diagPeano #-}++-- | Inductive step: distributes @f@ over argument 1, then recurses on tail.+instance HomArity n a b r fnB fnA+ => HomArity ('S n) a b r (b -> fnB) (a -> fnA) where+ onPeano f g x = onPeano @n f (g (f x))+ diagPeano f g x = diagPeano @n f (g (f x)) x+ {-# INLINE onPeano #-}+ {-# INLINE diagPeano #-}++-- | Ergonomic @Nat@-indexed wrapper for 'onPeano'.+--+-- >>> onN @2 (* 10) (,) 3 4+-- (30, 40)+--+-- >>> onN @3 show (,,) 1 2 3+-- ("1", "2", "3")+{-# INLINE onN #-}+onN :: forall (n :: Nat) a b r fnB fnA.+ HomArity (ToPeano n) a b r fnB fnA+ => (a -> b) -> fnB -> fnA+onN = onPeano @(ToPeano n)++-- | Ergonomic @Nat@-indexed diagonalization (replaces per-arity @dup@).+--+-- >>> diagN @2 (+) 5+-- 10+--+-- >>> diagN @3 (,,) "sky"+-- ("sky", "sky", "sky")+{-# INLINE diagN #-}+diagN :: forall (n :: Nat) a b r fnB fnA.+ HomArity (ToPeano n) a b r fnB fnA+ => (a -> b) -> fnB -> (a -> r)+diagN = diagPeano @(ToPeano n)++--------------------------------------------------------------------------------+-- 2. Applicative / Monadic Outward Lifting Over Arity `n` (`onMN`, `diagMN`)+--------------------------------------------------------------------------------++-- | Distributes an effectful function @a -> m b@ across @n@ arguments of a+-- pure constructor/function @b -> ... -> b -> r@, automatically lifting the+-- effect @m@ outward to produce @a -> ... -> a -> m r@.+class HomArityM (n :: Peano) (m :: Type -> Type) a b r fnB fnA+ | n m fnB a b -> r fnA+ , n m a b r -> fnB fnA+ where+ -- | Core inductive worker for 'onMN'.+ onMPeano :: Applicative m => (a -> m b) -> m fnB -> fnA++ -- | Core inductive worker for 'diagMN'.+ diagMPeano :: Applicative m => (a -> m b) -> m fnB -> (a -> m r)++-- | Base case: 0 arguments to lift.+instance HomArityM 'Z m a b r r (m r) where+ onMPeano _ mr = mr+ diagMPeano _ mr _ = mr+ {-# INLINE onMPeano #-}+ {-# INLINE diagMPeano #-}++-- | Inductive step: applies effectful argument via @(<*>)@ and recurses.+instance HomArityM n m a b r fnB fnA+ => HomArityM ('S n) m a b r (b -> fnB) (a -> fnA) where+ onMPeano f mg x = onMPeano @n f (mg <*> f x)+ diagMPeano f mg x = diagMPeano @n f (mg <*> f x) x+ {-# INLINE onMPeano #-}+ {-# INLINE diagMPeano #-}++-- | Distributes @f :: a -> m b@ across @n@ arguments of @g :: b -> ... -> b -> r@+-- and lifts @m@ outward to the result: @a -> ... -> a -> m r@.+--+-- >>> onMN @2 (\x -> Just (x + 1)) (,) 10 20+-- Just (11, 21)+{-# INLINE onMN #-}+onMN :: forall (n :: Nat) m a b r fnB fnA.+ (Applicative m, HomArityM (ToPeano n) m a b r fnB fnA)+ => (a -> m b) -> fnB -> fnA+onMN f g = onMPeano @(ToPeano n) f (pure g)++-- | Evaluates @f x@ @n@ times and lifts the effect @m@ outward over @g@.+--+-- >>> diagMN @2 (\x -> [x, -x]) (,) 5+-- [(5,5),(5,-5),(-5,5),(-5,-5)]+{-# INLINE diagMN #-}+diagMN :: forall (n :: Nat) m a b r fnB fnA.+ (Applicative m, HomArityM (ToPeano n) m a b r fnB fnA)+ => (a -> m b) -> fnB -> (a -> m r)+diagMN f g = diagMPeano @(ToPeano n) f (pure g)++--------------------------------------------------------------------------------+-- 3. Generalised Arity-`n` Zipping (`Zippy` & `zipWithN`)+--------------------------------------------------------------------------------++-- | Typeclass for containers supporting positional zipwise application.+class Functor f => ZipContainer f where+ -- | Pure repeater for zip application.+ zipPure :: a -> f a++ -- | Zipwise function application.+ zipAp :: f (a -> b) -> f a -> f b++-- | Instance for standard list.+instance ZipContainer [] where+ zipPure = repeat+ zipAp = zipWith ($)+ {-# INLINE zipPure #-}+ {-# INLINE zipAp #-}++-- | Instance for NonEmpty list.+instance ZipContainer NonEmpty where+ zipPure x = x :| repeat x+ zipAp (f :| fs) (x :| xs) = f x :| zipWith ($) fs xs+ {-# INLINE zipPure #-}+ {-# INLINE zipAp #-}++-- | Instance for Sequence.+instance ZipContainer Seq where+ zipPure = error "ZipContainer Seq: zipPure requires bounded target"+ zipAp = Seq.zipWith ($)+ {-# INLINE zipAp #-}++-- | Instance for Applicative ZipList.+instance ZipContainer ZipList where+ zipPure = pure+ zipAp = (<*>)+ {-# INLINE zipPure #-}+ {-# INLINE zipAp #-}++-- | Newtype wrapper endowing any 'ZipContainer' with its canonical Applicative instance.+newtype Zippy f a = Zippy { unZippy :: f a }+ deriving newtype (Eq, Ord, Show, Functor, Foldable)++-- | Applicative instance for 'Zippy'.+instance ZipContainer f => Applicative (Zippy f) where+ pure x = Zippy (zipPure x)+ Zippy fs <*> Zippy xs = Zippy (zipAp fs xs)+ {-# INLINE pure #-}+ {-# INLINE (<*>) #-}++-- | Inductively lifts an @n@-ary pure function @a1 -> ... -> an -> r@ into an+-- @n@-ary zipping function @f a1 -> ... -> f an -> f r@.+class ZipArity (n :: Peano) (f :: Type -> Type) fn zipFn+ | n f fn -> zipFn+ , n zipFn -> f fn+ where+ -- | Core inductive worker for 'zipWithN'.+ zipPeano :: ZipContainer f => f fn -> zipFn++-- | Base case: 0 remaining arguments.+instance ZipArity 'Z f r (f r) where+ zipPeano = id+ {-# INLINE zipPeano #-}++-- | Inductive step: consumes next container and recurses.+instance ZipArity n f fn zipFn+ => ZipArity ('S n) f (a -> fn) (f a -> zipFn) where+ zipPeano fs xs = zipPeano @n (zipAp fs xs)+ {-# INLINE zipPeano #-}++-- | Variadic @n@-ary @zipWith@ for any 'ZipContainer' ('[]', 'NonEmpty', etc.).+--+-- >>> zipWithN @3 (,,) [1, 2] ['a', 'b'] [True, False]+-- [(1, 'a', True), (2, 'b', False)]+{-# INLINE zipWithN #-}+zipWithN :: forall (n :: Nat) f fn zipFn.+ (ZipContainer f, ZipArity (ToPeano n) f fn zipFn)+ => fn -> zipFn+zipWithN f = zipPeano @(ToPeano n) (zipPure f)
+ src/Gongju/Evacuate.hs view
@@ -0,0 +1,248 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE UndecidableInstances #-}++-- | Module: Gongju.Evacuate+-- Description: Evacuability polymorphism bridging bounded-non-empty and evacuable collections+--+-- This module implements evacuability polymorphism ('Evacuable'), providing+-- a principled typeclass bridge between standard evacuable containers (@[]@, @Set@,+-- @Seq@, @Maybe@) that admit the empty state \(\emptyset\), and non-evacuable+-- containers (@NonEmpty@, @NESet@, @NESeq@) that carry a static non-emptiness proof+-- \(|C| \ge 1\).+--+-- = Architectural Context+--+-- Per Note [Evacuability Polymorphism] [ref:note-evacuability-polymorphism], filtering+-- non-empty collections in Haskell typically forces callers to downgrade to plain+-- lists, losing the strict non-empty type guarantee. 'Gongju.Evacuate' provides+-- total, bidirectional embeddings ('toEvac', 'fromEvac') into a canonical+-- 'EvacCarrier', enabling generic sifting ('sift'), withering ('witherEvac'), and+-- relational fibre-map aggregation ('insertEvac', 'groupEvac', 'groupEvacMany')+-- where keys with empty value containers evaporate automatically.+--+-- == Invariants & Guarantees+--+-- 1. __Preservation of Non-Emptiness:__ 'fromEvac' returns @Just@ if and only if+-- the underlying carrier satisfies the target container's non-emptiness invariants.+-- 2. __Automatic Key Evaporation:__ Relational aggregation functions ('insertEvac',+-- 'groupEvac', 'groupEvacMany') guarantee that no key maps to an evacuated (empty)+-- value structure.+-- 3. __Zero Runtime Allocation Overhead:__ Conversions between @NonEmpty@ and @[]@+-- or @NESet@ and @Set@ reuse underlying pointer structures.+--+-- = Worked Examples+--+-- >>> sift (> 1) (1 :| [2, 3]) :: Maybe (NonEmpty Int)+-- Just (2 :| [3])+--+-- >>> sift (> 5) (1 :| [2, 3]) :: Maybe (NonEmpty Int)+-- Nothing+--+-- >>> groupEvac [("a", 1), ("a", 2), ("b", 3)] :: Map.Map String (NonEmpty Int)+-- fromList [("a",1 :| [2]),("b",3 :| [])]+module Gongju.Evacuate+ ( -- * 1. Evacuability Polymorphism Typeclass+ Evacuable (..)+ -- * 2. Evacuability-Polymorphic Filtering & Wither Combinators+ , sift+ , mapMaybeEvac+ , witherEvac+ -- * 3. Relational & Semigroup-Fibre Map Aggregation+ , insertEvac+ , groupEvac+ , groupEvacMany+ ) where++import Data.Foldable qualified as Fold+import Data.Kind (Type)+import Data.List.NonEmpty (NonEmpty (..))+import Data.List.NonEmpty qualified as NonEmpty+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Sequence (Seq)+import Data.Set (Set)+import Data.Set qualified as Set+import Data.Set.NonEmpty (NESet)+import Data.Set.NonEmpty qualified as NESet+import Data.Sequence.NonEmpty (NESeq)+import Data.Sequence.NonEmpty qualified as NESeq+import Witherable (Filterable (..), Witherable (..))+import Witherable qualified as Wither++{- Note [Evacuability Polymorphism]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+[tag:note-evacuability-polymorphism]+Evacuability polymorphism bridges bounded-non-empty collections (NonEmpty, NESet, NESeq)+with standard evacuable collections ([], Set, Seq, Maybe) by abstracting over the common+carrier type and providing total conversions that safely witness emptiness or non-emptiness.+-}++--------------------------------------------------------------------------------+-- 1. Evacuable Class: Bridging C_{>= 0} and C_{>= 1} Containers+--------------------------------------------------------------------------------++-- | Unifies evacuable containers (@[]@, @Set@, @Seq@, @Maybe@) and non-evacuable+-- containers (@NonEmpty@, @NESet@, @NESeq@) over a shared 'EvacCarrier'.+--+-- The carrier must be a standard 'Filterable' instance permitting total filtering.+class Filterable (EvacCarrier c) => Evacuable (c :: Type -> Type) a where+ -- | Canonical evacuable container type representing the unconstrained collection.+ type EvacCarrier c :: Type -> Type++ -- | Total embedding from container @c a@ into its evacuable carrier.+ toEvac :: c a -> EvacCarrier c a++ -- | Conditional projection from the carrier back to @c a@.+ -- Returns @Just@ unconditionally for naturally evacuable targets, and witnesses+ -- non-emptiness (returning @Nothing@ if empty) for non-evacuable targets.+ fromEvac :: EvacCarrier c a -> Maybe (c a)++-- | Evacuable instance for standard lists.+instance Evacuable [] a where+ type EvacCarrier [] = []+ toEvac = id+ fromEvac = Just+ {-# INLINE toEvac #-}+ {-# INLINE fromEvac #-}++-- | Evacuable instance for 'NonEmpty' lists.+instance Evacuable NonEmpty a where+ type EvacCarrier NonEmpty = []+ toEvac = NonEmpty.toList+ fromEvac = NonEmpty.nonEmpty+ {-# INLINE toEvac #-}+ {-# INLINE fromEvac #-}++-- | Evacuable instance for 'Maybe'.+instance Evacuable Maybe a where+ type EvacCarrier Maybe = Maybe+ toEvac = id+ fromEvac = Just+ {-# INLINE toEvac #-}+ {-# INLINE fromEvac #-}++-- | Evacuable instance for 'Set'.+instance Ord a => Evacuable Set a where+ type EvacCarrier Set = []+ toEvac = Set.toList+ fromEvac = Just . Set.fromList+ {-# INLINE toEvac #-}+ {-# INLINE fromEvac #-}++-- | Evacuable instance for 'NESet'.+instance Ord a => Evacuable NESet a where+ type EvacCarrier NESet = []+ toEvac = Fold.toList+ fromEvac = fmap NESet.fromList . NonEmpty.nonEmpty+ {-# INLINE toEvac #-}+ {-# INLINE fromEvac #-}++-- | Evacuable instance for 'Seq'.+instance Evacuable Seq a where+ type EvacCarrier Seq = Seq+ toEvac = id+ fromEvac = Just+ {-# INLINE toEvac #-}+ {-# INLINE fromEvac #-}++-- | Evacuable instance for 'NESeq'.+instance Evacuable NESeq a where+ type EvacCarrier NESeq = Seq+ toEvac = NESeq.toSeq+ fromEvac = NESeq.nonEmptySeq+ {-# INLINE toEvac #-}+ {-# INLINE fromEvac #-}++--------------------------------------------------------------------------------+-- 2. Evacuability-Polymorphic Sifting & Mapping+--------------------------------------------------------------------------------++-- | Filters any container @c1 a@ (e.g. 'NonEmpty', 'NESet', or '[]') and converts+-- it into @Maybe (c2 a)@ (e.g. @Maybe (NESet a)@).+--+-- >>> sift (> 1) [1, 2, 3] :: Maybe [Int]+-- Just [2, 3]+{-# INLINE sift #-}+sift+ :: (Evacuable c1 a, Evacuable c2 a, EvacCarrier c1 ~ EvacCarrier c2)+ => (a -> Bool) -> c1 a -> Maybe (c2 a)+sift p = fromEvac . Wither.filter p . toEvac++-- | Maps and filters across any @c1 a@ into @Maybe (c2 b)@, changing element types freely.+--+-- >>> mapMaybeEvac (\x -> if even x then Just (x * 10) else Nothing) (1 :| [2, 3, 4]) :: Maybe (NonEmpty Int)+-- Just (20 :| [40])+{-# INLINE mapMaybeEvac #-}+mapMaybeEvac+ :: (Evacuable c1 a, Evacuable c2 b, EvacCarrier c1 ~ EvacCarrier c2)+ => (a -> Maybe b) -> c1 a -> Maybe (c2 b)+mapMaybeEvac f = fromEvac . Wither.mapMaybe f . toEvac++-- | Effectfully withers any @c1 a@ into @m (Maybe (c2 b))@.+{-# INLINE witherEvac #-}+witherEvac+ :: ( Applicative m+ , Evacuable c1 a+ , Evacuable c2 b+ , EvacCarrier c1 ~ EvacCarrier c2+ , Witherable (EvacCarrier c1)+ )+ => (a -> m (Maybe b)) -> c1 a -> m (Maybe (c2 b))+witherEvac f = fmap fromEvac . Wither.wither f . toEvac++--------------------------------------------------------------------------------+-- 3. Relational Semigroup-Fibre Map Aggregation+--------------------------------------------------------------------------------++-- | Inserts a container @c1 a@ (which may be empty after filtering!) into a+-- 'Map' of non-evacuable Semigroup containers @c2 a@ (such as 'NESet' or 'NonEmpty').+-- If @c1 a@ is empty, the map is untouched; if non-empty, it unions via '(<>)'.+{-# INLINE insertEvac #-}+insertEvac+ :: ( Ord k+ , Evacuable c1 a+ , Evacuable c2 a+ , EvacCarrier c1 ~ EvacCarrier c2+ , Semigroup (c2 a)+ )+ => k -> c1 a -> Map k (c2 a) -> Map k (c2 a)+insertEvac k xs m =+ case fromEvac (toEvac xs) of+ Nothing -> m+ Just ne -> Map.insertWith (<>) k ne m++-- | Groups key-value pairs @(k, a)@ into a @Map k (c a)@ for any @c@ ('NESet', 'NonEmpty', etc.).+--+-- >>> groupEvac [("odd", 1), ("even", 2), ("odd", 3)] :: Map String (NonEmpty Int)+-- fromList [("even",2 :| []),("odd",1 :| [3])]+{-# INLINE groupEvac #-}+groupEvac+ :: ( Foldable f+ , Ord k+ , Evacuable c a+ , EvacCarrier c ~ []+ , Semigroup (c a)+ )+ => f (k, a) -> Map k (c a)+groupEvac = Fold.foldl' (\acc (k, v) -> insertEvac k [v] acc) Map.empty++-- | Groups @(k, c1 a)@ pairs (where @c1 a@ can be a potentially-empty filtered list)+-- directly into a canonical @Map k (c2 a)@ (e.g. @Map Text (NESet Text)@),+-- automatically evaporating keys whose value container evacuated to empty.+{-# INLINE groupEvacMany #-}+groupEvacMany+ :: ( Foldable f+ , Ord k+ , Evacuable c1 a+ , Evacuable c2 a+ , EvacCarrier c1 ~ EvacCarrier c2+ , Semigroup (c2 a)+ )+ => f (k, c1 a) -> Map k (c2 a)+groupEvacMany = Fold.foldl' (\acc (k, vs) -> insertEvac k vs acc) Map.empty
+ src/Gongju/Spine.hs view
@@ -0,0 +1,221 @@+{-# LANGUAGE AllowAmbiguousTypes #-}+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE FunctionalDependencies #-}+{-# LANGUAGE PolyKinds #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE StandaloneKindSignatures #-}+{-# LANGUAGE TypeApplications #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE UndecidableInstances #-}++-- | Module: Gongju.Spine+-- Description: Arbitrary-depth interleaved Monad, Traversable, and Witherable spine traversal+--+-- This module implements zero-overhead arbitrary-depth spine traversal and contraction+-- combinators ('spineFor', 'forMN', 'spineWither', 'witherMN') over complex nested+-- monadic and traversable spines, eliminating nested @traverse . traverse@ and+-- @forMMMM@ boilerplate across multi-layered data structures.+--+-- = Architectural Context+--+-- Per Note [Spine Traversal Invariants] [ref:note-spine-traversal], working with+-- deeply nested effectful data pipelines (e.g., @IO [[Text]]@ or @Eff es [Seq a]@)+-- frequently leads to fragile, manual nesting of 'traverse' and monadic joins.+-- 'Gongju.Spine' provides a closed type family 'ClassifyLayer' that disambiguates+-- between the enclosing Monad @m@, an intermediate Traversable @t@, and the target+-- element layer at compile time without requiring overlapping typeclass instances.+--+-- == Invariants & Guarantees+--+-- 1. __Zero Overlapping Instances:__ By driving resolution through 'ClassifyLayer',+-- all instance selections are deterministic and strictly disjoint.+-- 2. __Automated Layer Fusion:__ Intermediate monadic actions are fused via @(>>=)@,+-- while traversable layers distribute via 'traverse' and witherable layers contract+-- via 'wither' in a single pass.+-- 3. __Totality & Inlining:__ All recursive operations expand to primitive GHC Core+-- binds and traverses via @{-# INLINE #-}@ pragmas.+--+-- = Worked Examples+--+-- >>> spineFor @2 (pure [[1, 2], [3]] :: IO [[Int]]) (pure . sum)+-- [3, 3]+--+-- >>> spineFor @3 (pure [[1, 2], [3]] :: IO [[Int]]) (pure . (* 10))+-- [[10, 20], [30]]+--+-- >>> spineWither @1 (pure [Just 1, Nothing, Just 3] :: IO [Maybe Int]) pure+-- [1, 3]+module Gongju.Spine+ ( -- * 1. Closed Type-Family Layer Classifier (Zero OverlappingInstances)+ LayerTag (..)+ , ClassifyLayer+ -- * 2. Arbitrary-Depth Interleaved Monad/Traversable Binding (`spineFor`, `forMN`)+ , SpineBind (..)+ , spineFor+ , forMN+ -- * 3. Arbitrary-Depth Witherable/Filterable Contraction (`spineWither`, `witherMN`)+ , SpineWither (..)+ , spineWither+ , witherMN+ ) where++import Data.Kind (Type)+import GHC.TypeNats (Nat)+import Witherable (Witherable (..))++import Gongju.Core (Peano (..), ToPeano)++{- Note [Spine Traversal]+~~~~~~~~~~~~~~~~~~~~~~~~~+[tag:note-spine-traversal]+Arbitrary-depth spine traversal performs depth-indexed interleaved monadic binding and+traversable distribution, peeling d outer layers to apply morphisms or withering predicates+at the leaf element with zero intermediate allocations.+-}++--------------------------------------------------------------------------------+-- 1. Disjoint Layer Classification+--------------------------------------------------------------------------------++-- | Classifies the role of an outer layer at depth @d@ relative to the target monad @m@.+data LayerTag+ = LayerTarget -- ^ Depth 0: reached the element/container target+ | LayerMonad -- ^ Outer layer is the active Monad @m@ itself (@join@ / @=<<@)+ | LayerTraversable -- ^ Outer layer is another Traversable @t@ (@traverse@)++-- | Closed type family inspecting a type representation to determine its 'LayerTag'+-- at depth @d@ with respect to active monad @m@.+type ClassifyLayer :: Peano -> (Type -> Type) -> Type -> LayerTag+type family ClassifyLayer d m spine where+ ClassifyLayer 'Z _ _ = 'LayerTarget+ ClassifyLayer ('S _) m (m _) = 'LayerMonad+ ClassifyLayer ('S _) _ (_ _) = 'LayerTraversable++--------------------------------------------------------------------------------+-- 2. Arbitrary-Depth Monad + Traversable Spine Traversal (`spineFor` / `forMN`)+--------------------------------------------------------------------------------++-- | Typeclass performing depth-indexed interleaved monadic and traversable traversal.+--+-- Inductively peels @d@ layers off @spine@, distributing intermediate @t@ layers+-- and binding intermediate @m@ layers until the leaf element @a@ is reached.+class SpineBind (d :: Peano) (tag :: LayerTag) (m :: Type -> Type) spine a b out+ | d tag m spine b -> out+ , d tag m spine -> a+ where+ -- | Core inductive worker for 'spineFor'.+ spineBindPeano :: Monad m => spine -> (a -> m b) -> m out++-- | Base case (d = 'Z): apply @a -> m b@ directly to the leaf element.+instance SpineBind 'Z 'LayerTarget m a a b b where+ spineBindPeano x f = f x+ {-# INLINE spineBindPeano #-}++-- | Inductive step 1: outer layer is @m@ itself -> bind via @(>>=)@.+instance ( nextTag ~ ClassifyLayer d m inner+ , SpineBind d nextTag m inner a b out+ )+ => SpineBind ('S d) 'LayerMonad m (m inner) a b out where+ spineBindPeano mx f = mx >>= \inner -> spineBindPeano @d @nextTag inner f+ {-# INLINE spineBindPeano #-}++-- | Inductive step 2: outer layer is a Traversable @t@ -> distribute via @traverse@.+instance ( Traversable t+ , nextTag ~ ClassifyLayer d m inner+ , SpineBind d nextTag m inner a b out+ )+ => SpineBind ('S d) 'LayerTraversable m (t inner) a b (t out) where+ spineBindPeano tx f = traverse (\inner -> spineBindPeano @d @nextTag inner f) tx+ {-# INLINE spineBindPeano #-}++-- | Traverses @d@ nested layers of @Monad m@ and @Traversable t@, applying+-- @a -> m b@ at depth @d@ and fusing all @m@ layers automatically.+--+-- >>> spineFor @2 (pure [[1, 2], [3]] :: IO [[Int]]) (pure . sum)+-- [3, 3] :: IO [Int]+--+-- >>> spineFor @3 (pure [[1, 2], [3]] :: IO [[Int]]) (pure . (* 10))+-- [[10, 20], [30]] :: IO [[Int]]+{-# INLINE spineFor #-}+spineFor+ :: forall (d :: Nat) m spine a b out.+ ( Monad m+ , SpineBind (ToPeano d) (ClassifyLayer (ToPeano d) m spine) m spine a b out+ )+ => spine -> (a -> m b) -> m out+spineFor = spineBindPeano @(ToPeano d) @(ClassifyLayer (ToPeano d) m spine)++-- | Flipped alias of 'spineFor' matching standard @mapM@ argument order.+{-# INLINE forMN #-}+forMN+ :: forall (d :: Nat) m spine a b out.+ ( Monad m+ , SpineBind (ToPeano d) (ClassifyLayer (ToPeano d) m spine) m spine a b out+ )+ => (a -> m b) -> spine -> m out+forMN = flip (spineFor @d)++--------------------------------------------------------------------------------+-- 3. Arbitrary-Depth Witherable Spine Contraction (`spineWither` / `witherMN`)+--------------------------------------------------------------------------------++-- | Typeclass performing depth-indexed spine withering and contraction.+--+-- Descends @d@ outer layers to locate a 'Witherable' container, applying+-- @a -> m (Maybe b)@ and evaporating filtered elements at the leaf level.+class SpineWither (d :: Peano) (tag :: LayerTag) (m :: Type -> Type) spine a b out+ | d tag m spine b -> out+ , d tag m spine -> a+ where+ -- | Core inductive worker for 'spineWither'.+ spineWitherPeano :: Monad m => spine -> (a -> m (Maybe b)) -> m out++-- | Base case (d = 'Z): target @w a@ is a Witherable container.+instance Witherable w => SpineWither 'Z 'LayerTarget m (w a) a b (w b) where+ spineWitherPeano wx f = wither f wx+ {-# INLINE spineWitherPeano #-}++-- | Inductive step 1: outer layer is @m@ itself -> bind via @(>>=)@.+instance ( nextTag ~ ClassifyLayer d m inner+ , SpineWither d nextTag m inner a b out+ )+ => SpineWither ('S d) 'LayerMonad m (m inner) a b out where+ spineWitherPeano mx f = mx >>= \inner -> spineWitherPeano @d @nextTag inner f+ {-# INLINE spineWitherPeano #-}++-- | Inductive step 2: outer layer is a Traversable @t@ -> distribute via @traverse@.+instance ( Traversable t+ , nextTag ~ ClassifyLayer d m inner+ , SpineWither d nextTag m inner a b out+ )+ => SpineWither ('S d) 'LayerTraversable m (t inner) a b (t out) where+ spineWitherPeano tx f = traverse (\inner -> spineWitherPeano @d @nextTag inner f) tx+ {-# INLINE spineWitherPeano #-}++-- | Descends @d@ outer layers of @Monad m@ / @Traversable t@ to a 'Witherable'+-- container @w a@, withering it with @a -> m (Maybe b)@ in a single pass.+--+-- Solves the @No instance for Witherable IO@ error directly:+-- >>> spineWither @1 (pure [Just 1, Nothing, Just 3] :: IO [Maybe Int]) pure+-- [1, 3] :: IO [Int]+{-# INLINE spineWither #-}+spineWither+ :: forall (d :: Nat) m spine a b out.+ ( Monad m+ , SpineWither (ToPeano d) (ClassifyLayer (ToPeano d) m spine) m spine a b out+ )+ => spine -> (a -> m (Maybe b)) -> m out+spineWither = spineWitherPeano @(ToPeano d) @(ClassifyLayer (ToPeano d) m spine)++-- | Flipped alias of 'spineWither' matching @for@ / @wither@ argument order.+{-# INLINE witherMN #-}+witherMN+ :: forall (d :: Nat) m spine a b out.+ ( Monad m+ , SpineWither (ToPeano d) (ClassifyLayer (ToPeano d) m spine) m spine a b out+ )+ => (a -> m (Maybe b)) -> spine -> m out+witherMN = flip (spineWither @d)
+ src/Gongju/Tuple.hs view
@@ -0,0 +1,167 @@+{-# LANGUAGE AllowAmbiguousTypes #-}+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE FunctionalDependencies #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeApplications #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE UndecidableInstances #-}++-- | Module: Gongju.Tuple+-- Description: Zero-cost currying isomorphisms and homogeneous tuple mapping+--+-- This module provides bidirectional isomorphisms between flat GHC tuples+-- and curried functions ('TupleCurry'), as well as homogeneous tuple+-- mapping and traversal combinators ('TupleHom') built directly on 'Gongju.Diagonal'.+--+-- = Architectural Context+--+-- Per Note [Gongju Combinator Taxonomy] [ref:note-gongju-combinators], flat tuples+-- in Haskell often require cumbersome boilerplate (or heavy dependencies like+-- @tuple-sop@) to map, traverse, or convert to curried forms.+-- 'Gongju.Tuple' solves this at zero runtime overhead using Peano-indexed+-- typeclass functional dependencies and unboxed GHC tuple constructors.+--+-- == Invariants & Guarantees+--+-- 1. __Zero-Cost Inlining:__ All operations ('curryFlat', 'uncurryFlat', 'mapTupleHom',+-- 'traverseTupleHom') are marked with @{-# INLINE #-}@ and eliminate to flat+-- constructor/pattern matching in GHC Core.+-- 2. __Purity & Totality:__ All operations are referentially transparent and total;+-- no partial functions or runtime errors exist in this module.+-- 3. __Preservation of Homogeneity:__ 'mapTupleHom' and 'traverseTupleHom'+-- guarantee that the structure and arity of homogeneous tuples are preserved.+--+-- = Worked Examples+--+-- >>> curryFlat (\(a, b) -> a + b) 10 20+-- 30+--+-- >>> uncurryFlat (+) (10, 20)+-- 30+--+-- >>> mapTupleHom (* 10) (1, 2, 3)+-- (10, 20, 30)+--+-- >>> traverseTupleHom Just (1, 2, 3)+-- Just (1, 2, 3)+module Gongju.Tuple+ ( -- * 1. Flat Tuple <-> Curried Arrow Bridge (`curryFlat`, `uncurryFlat`)+ TupleCurry (..)+ -- * 2. Homogeneous Flat Tuple Mapping & Traversal (`mapTupleHom`, `traverseTupleHom`)+ , TupleHom (..)+ ) where++import Gongju.Core (Peano (..))+import Gongju.Diagonal (onN, onMN)++--------------------------------------------------------------------------------+-- 1. Bidirectional Flat Tuple Currying Isomorphism+--------------------------------------------------------------------------------++-- | Typeclass establishing a bidirectional currying isomorphism between an+-- @n@-tuple @tup@ returning @r@ and its curried arrow representation @fn@.+--+-- The functional dependencies enforce that the tuple type and result uniquely+-- determine the Peano arity @n@ and curried function @fn@, and vice versa.+class TupleCurry (n :: Peano) tup r fn+ | tup r -> n fn+ , n fn -> tup r+ where+ -- | Converts a function over a flat tuple into its curried equivalent.+ --+ -- >>> curryFlat (\(x, y, z) -> x + y + z) 1 2 3+ -- 6+ curryFlat :: (tup -> r) -> fn++ -- | Converts a curried function into a function over a flat tuple.+ --+ -- >>> uncurryFlat (\x y z -> x + y + z) (1, 2, 3)+ -- 6+ uncurryFlat :: fn -> (tup -> r)++-- | 2-tuple isomorphism: @(a, b) -> r@ <-> @a -> b -> r@.+instance TupleCurry ('S ('S 'Z)) (a, b) r (a -> b -> r) where+ curryFlat f a b = f (a, b)+ uncurryFlat f (a, b) = f a b+ {-# INLINE curryFlat #-}+ {-# INLINE uncurryFlat #-}++-- | 3-tuple isomorphism: @(a, b, c) -> r@ <-> @a -> b -> c -> r@.+instance TupleCurry ('S ('S ('S 'Z))) (a, b, c) r (a -> b -> c -> r) where+ curryFlat f a b c = f (a, b, c)+ uncurryFlat f (a, b, c) = f a b c+ {-# INLINE curryFlat #-}+ {-# INLINE uncurryFlat #-}++-- | 4-tuple isomorphism: @(a, b, c, d) -> r@ <-> @a -> b -> c -> d -> r@.+instance TupleCurry ('S ('S ('S ('S 'Z)))) (a, b, c, d) r (a -> b -> c -> d -> r) where+ curryFlat f a b c d = f (a, b, c, d)+ uncurryFlat f (a, b, c, d) = f a b c d+ {-# INLINE curryFlat #-}+ {-# INLINE uncurryFlat #-}++-- | 5-tuple isomorphism: @(a, b, c, d, e) -> r@ <-> @a -> b -> c -> d -> e -> r@.+instance TupleCurry ('S ('S ('S ('S ('S 'Z))))) (a, b, c, d, e) r (a -> b -> c -> d -> e -> r) where+ curryFlat f a b c d e = f (a, b, c, d, e)+ uncurryFlat f (a, b, c, d, e) = f a b c d e+ {-# INLINE curryFlat #-}+ {-# INLINE uncurryFlat #-}++--------------------------------------------------------------------------------+-- 2. Homogeneous Tuple Distribution (Built Directly on `Gongju.Diagonal`)+--------------------------------------------------------------------------------++-- | Typeclass for homogeneous tuples whose component slots all share a single+-- element type @a@, supporting mapping to @tupB@ (with element type @b@)+-- and Applicative traversal.+class TupleHom tupA tupB a b | tupA -> a, tupB -> b, tupA b -> tupB, tupB a -> tupA where+ -- | Distributes a pure morphism @a -> b@ over every slot of a homogeneous tuple:+ --+ -- \[+ -- \text{mapTupleHom}\;f\;(x_1, \dots, x_k) = (f\;x_1, \dots, f\;x_k)+ -- \]+ --+ -- >>> mapTupleHom (+ 1) (10, 20, 30)+ -- (11, 21, 31)+ mapTupleHom :: (a -> b) -> tupA -> tupB++ -- | Distributes an effectful morphism @a -> m b@ over every slot of a homogeneous+ -- tuple and lifts the enclosing Applicative effect @m@ outward:+ --+ -- \[+ -- \text{traverseTupleHom}\;f\;(x_1, \dots, x_k) = (,,...)\;\langle\$\rangle\;f\;x_1\;\langle*\rangle\;\dots\;\langle*\rangle\;f\;x_k+ -- \]+ --+ -- >>> traverseTupleHom (\x -> if x > 0 then Just (x * 2) else Nothing) (1, 2, 3)+ -- Just (2, 4, 6)+ traverseTupleHom :: Applicative m => (a -> m b) -> tupA -> m tupB++-- | Homogeneous 2-tuple instance.+instance TupleHom (a, a) (b, b) a b where+ mapTupleHom f = uncurryFlat (onN @2 f (,))+ traverseTupleHom f = uncurryFlat (onMN @2 f (,))+ {-# INLINE mapTupleHom #-}+ {-# INLINE traverseTupleHom #-}++-- | Homogeneous 3-tuple instance.+instance TupleHom (a, a, a) (b, b, b) a b where+ mapTupleHom f = uncurryFlat (onN @3 f (,,))+ traverseTupleHom f = uncurryFlat (onMN @3 f (,,))+ {-# INLINE mapTupleHom #-}+ {-# INLINE traverseTupleHom #-}++-- | Homogeneous 4-tuple instance.+instance TupleHom (a, a, a, a) (b, b, b, b) a b where+ mapTupleHom f = uncurryFlat (onN @4 f (,,,))+ traverseTupleHom f = uncurryFlat (onMN @4 f (,,,))+ {-# INLINE mapTupleHom #-}+ {-# INLINE traverseTupleHom #-}++-- | Homogeneous 5-tuple instance.+instance TupleHom (a, a, a, a, a) (b, b, b, b, b) a b where+ mapTupleHom f = uncurryFlat (onN @5 f (,,,,))+ traverseTupleHom f = uncurryFlat (onMN @5 f (,,,,))+ {-# INLINE mapTupleHom #-}+ {-# INLINE traverseTupleHom #-}
test/Main.hs view
@@ -25,7 +25,7 @@ import Test.Hspec import Data.Functor.Identity (Identity (..))-import Gongju.Core+import Gongju import CoreInspection -- | Minimal Comonad fixture for verifying cokleisli extension via 'W'.@@ -78,7 +78,7 @@ in runIxState (k a) j main :: IO ()-main = hspec do+main = hspec $ parallel do -- Tested against Note [Peano TypeLits Bridge] [ref:note-peano-typelits-bridge] describe "Gongju.Peano Naturals & List Type Families" do it "converts numeric TypeLits to Peano and verifies term equality" do@@ -514,6 +514,42 @@ testYankCat1 (-) 5 20 `shouldBe` 15 testPermuteCat3 f3 3 1 2 `shouldBe` 123 testPermuteHandler3 f4 3 1 2 4 `shouldBe` 1234++ describe "Gongju.Diagonal Arity Distribution and Variadic Zipping" do+ it "onN distributes unary function across curried arguments" do+ onN @2 (* 10) (,) (3 :: Int) (4 :: Int) `shouldBe` (30, 40)+ onN @3 show (,,) (1 :: Int) (2 :: Int) (3 :: Int) `shouldBe` ("1", "2", "3")++ it "diagN collapses curried function along the diagonal" do+ diagN @2 id (+) (5 :: Int) `shouldBe` 10+ diagN @3 id (,,) ("sky" :: String) `shouldBe` ("sky", "sky", "sky")++ it "zipWithN variadically zips arbitrary ZipContainers" do+ zipWithN @3 (,,) ([1, 2] :: [Int]) (['a', 'b'] :: [Char]) ([True, False] :: [Bool]) `shouldBe` ([(1, 'a', True), (2, 'b', False)] :: [(Int, Char, Bool)])++ describe "Gongju.Evacuate Carrier Polymorphism" do+ it "converts to and from evacuable carriers" do+ toEvac ([1, 2, 3] :: [Int]) `shouldBe` [1, 2, 3]+ fromEvac ([1, 2] :: [Int]) `shouldBe` (Just [1, 2] :: Maybe [Int])++ it "sifts evacuable containers with boolean predicate" do+ sift even ([1, 2, 3, 4] :: [Int]) `shouldBe` (Just [2, 4] :: Maybe [Int])+ mapMaybeEvac (\x -> if even x then Just (show x) else Nothing) ([1, 2, 3, 4] :: [Int]) `shouldBe` (Just ["2", "4"] :: Maybe [String])++ describe "Gongju.Spine Arbitrary-Depth Monad + Traversable Traversal" do+ it "spineFor traverses nested layers and applies pure morphism" do+ spineFor @2 (Just [1 :: Int, 2, 3]) (pure . (* 2)) `shouldBe` (Just [2, 4, 6] :: Maybe [Int])++ it "spineWither contracts and withers nested spine layers" do+ spineWither @1 (Just [Just (1 :: Int), Nothing, Just 3]) pure `shouldBe` (Just [1, 3] :: Maybe [Int])++ describe "Gongju.Tuple Flat Tuple Combinators" do+ it "curryFlat and uncurryFlat bridge tuples and curried functions" do+ curryFlat (\(x, y, z) -> x + y + z) (1 :: Int) (2 :: Int) (3 :: Int) `shouldBe` 6+ uncurryFlat (\x y z -> x + y + z) (1 :: Int, 2 :: Int, 3 :: Int) `shouldBe` 6++ it "mapTupleHom maps homogeneous tuples" do+ mapTupleHom (* 10) (1 :: Int, 2 :: Int, 3 :: Int) `shouldBe` (10, 20, 30)