packages feed

tuple-classes (empty) → 1.0.0

raw patch · 10 files changed

+999/−0 lines, 10 filesdep +assocdep +basedep +binarysetup-changed

Dependencies added: assoc, base, binary, deepseq, hashable, strict, template-haskell, tuple-classes

Files

+ CHANGELOG.md view
@@ -0,0 +1,4 @@+# Changelog and Acknowledgments++## 1.0.0+* Initial release.
+ LICENSE view
@@ -0,0 +1,203 @@++                                 Apache License+                           Version 2.0, January 2004+                        http://www.apache.org/licenses/++   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++   1. Definitions.++      "License" shall mean the terms and conditions for use, reproduction,+      and distribution as defined by Sections 1 through 9 of this document.++      "Licensor" shall mean the copyright owner or entity authorized by+      the copyright owner that is granting the License.++      "Legal Entity" shall mean the union of the acting entity and all+      other entities that control, are controlled by, or are under common+      control with that entity. For the purposes of this definition,+      "control" means (i) the power, direct or indirect, to cause the+      direction or management of such entity, whether by contract or+      otherwise, or (ii) ownership of fifty percent (50%) or more of the+      outstanding shares, or (iii) beneficial ownership of such entity.++      "You" (or "Your") shall mean an individual or Legal Entity+      exercising permissions granted by this License.++      "Source" form shall mean the preferred form for making modifications,+      including but not limited to software source code, documentation+      source, and configuration files.++      "Object" form shall mean any form resulting from mechanical+      transformation or translation of a Source form, including but+      not limited to compiled object code, generated documentation,+      and conversions to other media types.++      "Work" shall mean the work of authorship, whether in Source or+      Object form, made available under the License, as indicated by a+      copyright notice that is included in or attached to the work+      (an example is provided in the Appendix below).++      "Derivative Works" shall mean any work, whether in Source or Object+      form, that is based on (or derived from) the Work and for which the+      editorial revisions, annotations, elaborations, or other modifications+      represent, as a whole, an original work of authorship. For the purposes+      of this License, Derivative Works shall not include works that remain+      separable from, or merely link (or bind by name) to the interfaces of,+      the Work and Derivative Works thereof.++      "Contribution" shall mean any work of authorship, including+      the original version of the Work and any modifications or additions+      to that Work or Derivative Works thereof, that is intentionally+      submitted to Licensor for inclusion in the Work by the copyright owner+      or by an individual or Legal Entity authorized to submit on behalf of+      the copyright owner. For the purposes of this definition, "submitted"+      means any form of electronic, verbal, or written communication sent+      to the Licensor or its representatives, including but not limited to+      communication on electronic mailing lists, source code control systems,+      and issue tracking systems that are managed by, or on behalf of, the+      Licensor for the purpose of discussing and improving the Work, but+      excluding communication that is conspicuously marked or otherwise+      designated in writing by the copyright owner as "Not a Contribution."++      "Contributor" shall mean Licensor and any individual or Legal Entity+      on behalf of whom a Contribution has been received by Licensor and+      subsequently incorporated within the Work.++   2. Grant of Copyright License. Subject to the terms and conditions of+      this License, each Contributor hereby grants to You a perpetual,+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable+      copyright license to reproduce, prepare Derivative Works of,+      publicly display, publicly perform, sublicense, and distribute the+      Work and such Derivative Works in Source or Object form.++   3. Grant of Patent License. Subject to the terms and conditions of+      this License, each Contributor hereby grants to You a perpetual,+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable+      (except as stated in this section) patent license to make, have made,+      use, offer to sell, sell, import, and otherwise transfer the Work,+      where such license applies only to those patent claims licensable+      by such Contributor that are necessarily infringed by their+      Contribution(s) alone or by combination of their Contribution(s)+      with the Work to which such Contribution(s) was submitted. If You+      institute patent litigation against any entity (including a+      cross-claim or counterclaim in a lawsuit) alleging that the Work+      or a Contribution incorporated within the Work constitutes direct+      or contributory patent infringement, then any patent licenses+      granted to You under this License for that Work shall terminate+      as of the date such litigation is filed.++   4. Redistribution. You may reproduce and distribute copies of the+      Work or Derivative Works thereof in any medium, with or without+      modifications, and in Source or Object form, provided that You+      meet the following conditions:++      (a) You must give any other recipients of the Work or+          Derivative Works a copy of this License; and++      (b) You must cause any modified files to carry prominent notices+          stating that You changed the files; and++      (c) You must retain, in the Source form of any Derivative Works+          that You distribute, all copyright, patent, trademark, and+          attribution notices from the Source form of the Work,+          excluding those notices that do not pertain to any part of+          the Derivative Works; and++      (d) If the Work includes a "NOTICE" text file as part of its+          distribution, then any Derivative Works that You distribute must+          include a readable copy of the attribution notices contained+          within such NOTICE file, excluding those notices that do not+          pertain to any part of the Derivative Works, in at least one+          of the following places: within a NOTICE text file distributed+          as part of the Derivative Works; within the Source form or+          documentation, if provided along with the Derivative Works; or,+          within a display generated by the Derivative Works, if and+          wherever such third-party notices normally appear. The contents+          of the NOTICE file are for informational purposes only and+          do not modify the License. You may add Your own attribution+          notices within Derivative Works that You distribute, alongside+          or as an addendum to the NOTICE text from the Work, provided+          that such additional attribution notices cannot be construed+          as modifying the License.++      You may add Your own copyright statement to Your modifications and+      may provide additional or different license terms and conditions+      for use, reproduction, or distribution of Your modifications, or+      for any such Derivative Works as a whole, provided Your use,+      reproduction, and distribution of the Work otherwise complies with+      the conditions stated in this License.++   5. Submission of Contributions. Unless You explicitly state otherwise,+      any Contribution intentionally submitted for inclusion in the Work+      by You to the Licensor shall be under the terms and conditions of+      this License, without any additional terms or conditions.+      Notwithstanding the above, nothing herein shall supersede or modify+      the terms of any separate license agreement you may have executed+      with Licensor regarding such Contributions.++   6. Trademarks. This License does not grant permission to use the trade+      names, trademarks, service marks, or product names of the Licensor,+      except as required for reasonable and customary use in describing the+      origin of the Work and reproducing the content of the NOTICE file.++   7. Disclaimer of Warranty. Unless required by applicable law or+      agreed to in writing, Licensor provides the Work (and each+      Contributor provides its Contributions) on an "AS IS" BASIS,+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+      implied, including, without limitation, any warranties or conditions+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+      PARTICULAR PURPOSE. You are solely responsible for determining the+      appropriateness of using or redistributing the Work and assume any+      risks associated with Your exercise of permissions under this License.++   8. Limitation of Liability. In no event and under no legal theory,+      whether in tort (including negligence), contract, or otherwise,+      unless required by applicable law (such as deliberate and grossly+      negligent acts) or agreed to in writing, shall any Contributor be+      liable to You for damages, including any direct, indirect, special,+      incidental, or consequential damages of any character arising as a+      result of this License or out of the use or inability to use the+      Work (including but not limited to damages for loss of goodwill,+      work stoppage, computer failure or malfunction, or any and all+      other commercial damages or losses), even if such Contributor+      has been advised of the possibility of such damages.++   9. Accepting Warranty or Additional Liability. While redistributing+      the Work or Derivative Works thereof, You may choose to offer,+      and charge a fee for, acceptance of support, warranty, indemnity,+      or other liability obligations and/or rights consistent with this+      License. However, in accepting such obligations, You may act only+      on Your own behalf and on Your sole responsibility, not on behalf+      of any other Contributor, and only if You agree to indemnify,+      defend, and hold each Contributor harmless for any liability+      incurred by, or claims asserted against, such Contributor by reason+      of your accepting any such warranty or additional liability.++   END OF TERMS AND CONDITIONS++   APPENDIX: How to apply the Apache License to your work.++      To apply the Apache License to your work, attach the following+      boilerplate notice, with the fields enclosed by brackets "[]"+      replaced with your own identifying information. (Don't include+      the brackets!)  The text should be enclosed in the appropriate+      comment syntax for the file format. We also recommend that a+      file or class name and description of purpose be included on the+      same "printed page" as the copyright notice for easier+      identification within third-party archives.++   Copyright [yyyy] [name of copyright owner]++   Licensed under the Apache License, Version 2.0 (the "License");+   you may not use this file except in compliance with the License.+   You may obtain a copy of the License at++       http://www.apache.org/licenses/LICENSE-2.0++   Unless required by applicable law or agreed to in writing, software+   distributed under the License is distributed on an "AS IS" BASIS,+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+   See the License for the specific language governing permissions and+   limitations under the License.+
+ README.md view
@@ -0,0 +1,77 @@+# tuple-classes++Haskell facilities for manipulating _n_-ary tuples and functions in lazy and strict varieties, plus strict tuples.++```haskell+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE TypeApplications #-}++import Data.Tuple.Classes (curryN', uncurryN')++-- Function wrapper that expects a unary function+printArgAndRun :: (Show a) => (a -> IO b) -> a -> IO b+printArgAndRun f x = do+    print x+    f x++-- But we have a ternary function+printTitleAndSum :: String -> Int -> Int -> IO ()+printTitleAndSum title i j = do+    putStrLn title+    print $ i + j++-- We can adapt them+printArgsTitleAndSum :: String -> Int -> Int -> IO ()+printArgsTitleAndSum =+    curryN' @3 $ printArgAndRun $ uncurryN' @3 printTitleAndSum++main :: IO ()+main = printArgsTitleAndSum "Important identity" 26885 15184+```+```+StrictTuple3 "Important identity" 26885 15184+Important identity+42069+```++```haskell+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE TypeApplications #-}++module DocTest02 (main) where++import Data.Tuple.Classes (TupleAt(..))++consTuple :: (TupleAt 1 a t u) => a -> t -> u+consTuple = tupleInsert @1++main :: IO ()+main = print $ consTuple 'x' $ consTuple False ("sequitur", "quodlibet")+```+```+('x',False,"sequitur","quodlibet")+```++## Prior art++* Edward Kmett's lens's [`Field1` etc.](https://hackage-content.haskell.org/package/lens-5.3.6/docs/Control-Lens-Tuple.html) and [`Each`](https://hackage-content.haskell.org/package/lens-5.3.6/docs/Control-Lens-Each.html#t:Each)+* Lennart Augustsson's [`Curry`](https://hackage.haskell.org/package/tuple-0.3.0.2/docs/Data-Tuple-Curry.html) class+* Mitchell Rosen's [strict-tuple](https://hackage.haskell.org/package/strict-tuple-0.1.5.4/docs/Data-Tuple-Strict.html) which unfortunately would need some unnecessary-looking breaking changes to suit this library:+  * Removing `Biapplicative` instances in order to not depend on the heavy bifunctors package+  * Removing `T1` and `T2` which conflict with the much more supported `Identity` and `Pair`+* [mangoiv's proof-of-concept](https://bin.mangoiv.com/note?id=d204d07f-6292-4eb7-9aff-4cabc78394b9) related to keyword args and arbitrary function arity++Credit to mango for suggesting the limitations of that approach and indirectly shaping this library's design.++## LLM contribution policy++https://en.wikipedia.org/wiki/TESCREAL++## License++[Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0.html).++## Main Author++©2026 Steven Shuck
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ src/Data/Tuple/Classes.hs view
@@ -0,0 +1,176 @@+{-# LANGUAGE AllowAmbiguousTypes #-}+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE FunctionalDependencies #-}+{-# LANGUAGE ImplicitParams #-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE TypeFamilies #-}++{-# OPTIONS_GHC -Wno-orphans #-}++module Data.Tuple.Classes (+    -- | We present utilities here for generalized handling of tuples:+    --+    -- * inserting and removing fields+    -- * converting /n/-ary functions to unary and vice versa+    -- * re-exports of smaller tuples+    -- * larger strict tuples with relevant instances+    --+    -- We consider `Identity` the canonical strict tuple insofar as it adds no extra laziness.+    --+    -- === __Discussion__+    --+    -- Tuples are the way to anonymously package up potentially heterogeneous values as a single value in Haskell.+    -- (We say /anonymously/ because they have unnamed fields and thus suffer from a kind of semantic blindness.+    -- Consider defining a proper record type if you are not simply solving a localized problem of needing a single value.)+    --+    -- Unlike in Python for example, we cannot freely convert between a tuple and other types in Haskell.+    -- The issue boils down to differently-sized tuples having different numbers of type parameters.+    -- Even to access the third field of a tuple of arbitrary size, we must write out (or generate, as we do here) separate implementations covering every tuple size up to some finite number (here, 9), and thread however many type and data parameters through each definition.+    -- The best we can do to avoid an API with sprawling identifiers is offer multi-param typeclasses that can accomodate all these variables.+    --+    -- An important use case for generalized tupling\/untupling is conversion between functions of one argument and those of /n/ arguments.+    -- Functions are curried, which means that every function really takes one argument and has another function as its result.+    -- As a type construction, a function of multiple arguments is a nested type:+    --+    -- >   a ->      b ->      c ->      d ->   e+    -- >   a ->   (  b ->   (  c ->   (  d ->   e)))+    -- > ((->) a) (((->) b) (((->) c) (((->) d) e)))+    --+    -- It is not possible to write a type-level function to plumb these layers automatically and emit a single type.+    -- We /could/ write a closed type family requiring @UndecidableInstances@:+    --+    -- @+    -- type family Arity f :: Nat where+    --     Arity (a -> b) = 1 + Arity b+    --     Arity a        = 0+    --+    -- arity :: (KnownNat (Arity f)) => f -> Natural+    -- arity _ = natVal $ Proxy @(Arity a)+    -- @+    --+    -- but this falls short.+    -- If the final type is a variable, GHC cannot prove that it is not a function.+    --+    -- >>> arity (++)+    -- 2+    -- >>> arity print+    -- 1+    -- >>> arity id+    --         • No instance for ‘KnownNat (1 + Arity a0)’+    --+    -- For more food for thought, see [this sketch](https://bin.mangoiv.com/note?id=d204d07f-6292-4eb7-9aff-4cabc78394b9) for Haskell keyword arguments.+    --+    -- Even if this type family were possible, the emitted type still could not be a simple tuple without the support of a typeclass and rote instances, for the reason listed above.++    -- * Resizing tuples+    TupleAt(..),+    ith,++    -- * Generalized uncurrying+    UncurryN(..),++    -- * Re-exports+    Solo(..),+    Identity(..),+    Strict.Pair(..),+    type (Strict.:!:),++    -- * Additional strict tuples+    StrictTuple3(..),+    StrictTuple4(..),+    StrictTuple5(..),+    StrictTuple6(..),+    StrictTuple7(..),+    StrictTuple8(..),+    StrictTuple9(..),+) where++import Data.Functor.Identity (Identity(..))+import Data.Strict.Tuple     qualified as Strict+import Data.Tuple            (Solo(..))+import GHC.TypeNats          (Nat)++import Data.Tuple.Classes.TH++-- | A relation between an @n@-ary function @c@ and unary functions of lazy and strict tuple arguments, along with methods to convert between them.+--+-- Use methods with @TypeApplications@/@DataKinds@:+--+-- >>> f = printf "The %s br%dwn fo%c\n" :: String -> Int -> Char -> IO ()+-- >>> mapM_ (uncurryN @3 f) [("quick", 0, 'x'), ("employee", -86, '臭')]+-- The quick br0wn fox+-- The employee br-86wn fo臭+class UncurryN (n :: Nat) c where+    -- | A unary function isomorphic to @c@.+    -- The argument is a lazy tuple.+    type UncurriedN n c+    -- | Same, but the tuple is strict.+    type UncurriedN' n c+    -- | Convert a function taking @n@ arguments to a function taking a single lazy @n@-tuple.+    --+    -- > uncurryN :: (a -> b -> ... -> r) -> (a, b, ...) -> r+    --+    -- If the function @cur _ _ ... = k@ ignores its arguments, then @uncurryN cur ⊥ = k@.+    uncurryN :: c -> UncurriedN n c+    -- | Convert a function taking a single lazy @n@-tuple to a function taking @n@ arguments.+    --+    -- > curryN :: ((a, b, ...) -> r) -> a -> b -> ... -> r+    curryN :: UncurriedN n c -> c+    -- | Convert a function taking @n@ arguments to a function taking a single strict @n@-tuple.+    --+    -- > uncurryN' :: (a -> b -> ... -> r) -> StrictTupleN a b ... -> r+    --+    -- If the function @cur _ _ ... = k@ ignores its arguments, then @uncurryN' cur ⊥ = k@.+    uncurryN' :: c -> UncurriedN' n c+    -- | Convert a function taking a single strict @n@-tuple to a function taking @n@ arguments.+    --+    -- > curryN' :: (StrictTupleN a b ... -> r) -> a -> b -> ... -> r+    curryN' :: UncurriedN' n c -> c++-- | Inserting and removing tuple fields.+-- Specify @i@ via @TypeApplications@/@DataKinds@.+--+-- * @i@: the 1-based index of the inserted or removed field.+-- * @a@: the type of the inserted or removed field.+-- * @t@: the narrower tuple \(to be inserted into or resulting from a removal).+-- * @u@: the wider tuple \(resulting from an insertion or from which to remove something).+--+-- > tupleRemove @i . uncurry (tupleInsert @i) = id+-- > uncurry (tupleInsert @i) . tupleRemove @i = id+--+-- The valid range of @i@ is \[1, /n/], where /n/ is the width of @u@.+class TupleAt (i :: Nat) a t u | i a t -> u, i u -> a t where+    -- | Insert an @a@ into @t@ at @i@ and return the widened tuple @u@.+    -- Upon insertion, any fields at indices >=@i@ will slide to the right to make room.+    --+    -- >>> tupleInsert @3 42.0 ("Hello", (), True)+    -- ("Hello",(),42.0,True)+    -- >>> tupleInsert @2 'x' (Identity 67)+    -- 67 :!: 'x'+    --+    -- For lazy tuples, @`ith` \@i \(tupleInsert \@i x ⊥) = x@.+    --+    -- For strict tuples, @ith \@i \(tupleInsert \@i x ⊥) = ⊥@.+    tupleInsert :: a -> t -> u+    -- | Remove an @a@ from @u@ at @i@ and return both it and the remaining tuple @t@.+    -- Upon removal, any fields at indices >@i@ will slide to the left to close the gap.+    --+    -- >>> tupleRemove @1 ("Hello", (), 42.0, True)+    -- ("Hello",((),42.0,True))+    tupleRemove :: u -> (a, t)++-- | Access the @i@th field of a tuple.+-- Generalization of @fst@/@snd@.+--+-- >>> ith @1 (Foo, "bar")+-- Foo+--+-- This is a convenience function defined as @fst . tupleRemove \@i@.+-- For typeclasses purpose-built for accessing tuple fields, consider [lens\'s @Field1@ and the like](https://hackage-content.haskell.org/package/lens-5.3.6/docs/Control-Lens-Tuple.html).+-- We do not wish to duplicate that here; it is already duplicated by (the excellent) [microlens](https://hackage-content.haskell.org/package/microlens-0.5.0.0/docs/Lens-Micro-FieldN.html).+ith :: forall i a t u. (TupleAt i a t u) => u -> a+ith = fst . tupleRemove @i++$(foldMap (\n -> let ?n = n in makeStrictTupleAndInsts) [3 .. 9])+$(mapM    (\n -> let ?n = n in makeUncurryNInst)        [0 .. 9])+$(foldMap (\n -> let ?n = n in makeTupleAtInsts)        [2 .. 9])
+ src/Data/Tuple/Classes/TH.hs view
@@ -0,0 +1,393 @@+{-# LANGUAGE ImplicitParams #-}+{-# LANGUAGE TemplateHaskellQuotes #-}++module Data.Tuple.Classes.TH (+    makeStrictTupleAndInsts,+    makeUncurryNInst,+    makeTupleAtInsts,+) where++import Control.DeepSeq       (NFData(..), NFData1, NFData2(..))+import Control.Monad         (forM)+import Data.Bifoldable       (Bifoldable(..))+import Data.Bifunctor        (Bifunctor(..))+import Data.Bifunctor.Swap   (Swap(..))+import Data.Binary           (Binary(..))+import Data.Bitraversable    (Bitraversable(..))+import Data.Functor.Classes  (Eq1(..), Eq2(..))+import Data.Functor.Identity (Identity(..))+import Data.Hashable         (Hashable)+import Data.Hashable.Lifted  (Hashable1)+import Data.Strict.Classes   (Strict(..))+import Data.Strict.Tuple     (Pair(..))+import GHC.Generics          (Generic, Generic1)+import Language.Haskell.TH   hiding (Strict, strictType)++strictTName :: Int -> Name+strictTName 0 = ''()+strictTName 1 = ''Identity+strictTName 2 = ''Pair+strictTName n = mkName $ "StrictTuple" ++ show n++strictDName :: Int -> Name+strictDName 0 = '()+strictDName 1 = 'Identity+strictDName 2 = '(:!:)+strictDName n = strictTName n++dropLast :: (?n :: Int) => Int -> [a] -> [a]+dropLast u = take $ ?n - u++-- StrictTuple3+mkNames :: (?n :: Int) => (Enum a) => a -> (a -> String) -> [Name]+mkNames x toName = map (mkName . toName) $ take ?n $ enumFrom x++abc, xs, ys :: (?n :: Int) => [Name]+-- a, b, c+abc = mkNames 'a' (: [])+-- x0, x1, x2+xs = mkNames (0 :: Int) $ ('x' :) . show+-- y0, y1, y2+ys = mkNames (0 :: Int) $ ('y' :) . show++fName, gName, cur, unc :: Name+fName = mkName "f"+gName = mkName "g"+cur = mkName "cur"+unc = mkName "unc"++-- !a+banged :: Name -> BangTypeQ+banged a = bangType (bang noSourceUnpackedness sourceStrict) (varT a)++-- StrictTuple3 a+strictTupleUnsatT :: (?n :: Int) => Int -> TypeQ+strictTupleUnsatT u =+    foldl' appT (conT $ strictTName ?n) $ dropLast u $ map varT abc++-- StrictTuple3 a b c+strictTupleSatT :: (?n :: Int) => TypeQ+strictTupleSatT = strictTupleUnsatT 0++-- (a, b, c)+lazyTupleSatT :: (?n :: Int) => TypeQ+lazyTupleSatT = foldl' appT (tupleT ?n) $ map varT abc++-- StrictTuple3 x0 x1 x2+strictTupleP :: (?n :: Int) => [Name] -> PatQ+strictTupleP = conP (strictDName ?n) . map varP++-- StrictTuple3 x0+strictTupleUnsatE :: (?n :: Int) => Int -> ExpQ+strictTupleUnsatE u =+    foldl' appE (conE $ strictDName ?n) $ dropLast u $ map varE xs++-- StrictTuple3 x0 x1 x2+strictTupleSatE :: (?n :: Int) => ExpQ+strictTupleSatE = strictTupleUnsatE 0++{-+instance UncurryN 3 (a -> b -> c -> d) where+    type UncurriedN 3 (a -> b -> c -> d) = (a, b, c) -> d+    type UncurriedN' 3 (a -> b -> c -> d) = StrictTuple3 a b c -> d+    uncurryN cur ~(x0, x1, x2) = cur x0 x1 x2+    curryN unc x0 x1 x2 = unc (x0, x1, x2)+    uncurryN' cur ~(StrictTuple3 x0 x1 x2) = cur x0 x1 x2+    curryN' unc x0 x1 x2 = unc (StrictTuple3 x0 x1 x2)+-}+makeUncurryNInst :: (?n :: Int) => DecQ+makeUncurryNInst =+    let d = mkName [['a' ..] !! ?n]+        nT = litT $ numTyLit $ fromIntegral ?n+        curT = foldr (\a r -> [t| $(varT a) -> $r |]) (varT d) abc+        uncurryClause ctor = clause+            [varP cur, tildeP $ conP ctor $ map varP xs]+            (normalB $ foldl' appE (varE cur) $ map varE xs)+            []+        curryClause ctor = clause+            (map varP $ unc : xs)+            (normalB $ varE unc `appE` foldl' appE (conE ctor) (map varE xs))+            []+    in instanceD+        (pure [])+        [t| $(conT $ mkName "UncurryN") $nT $curT |]+        [+            tySynInstD $ tySynEqn+                Nothing+                [t| $(conT $ mkName "UncurriedN") $nT $curT |]+                [t| $lazyTupleSatT -> $(varT d) |],+            tySynInstD $ tySynEqn+                Nothing+                [t| $(conT $ mkName "UncurriedN'") $nT $curT |]+                [t| $strictTupleSatT -> $(varT d) |],+            funD (mkName "uncurryN") [uncurryClause $ tupleDataName ?n],+            funD (mkName "curryN") [curryClause $ tupleDataName ?n],+            funD (mkName "uncurryN'") [uncurryClause $ strictDName ?n],+            funD (mkName "curryN'") [curryClause $ strictDName ?n]]++makeTupleAtInsts :: (?n :: Int) => DecsQ+makeTupleAtInsts = fmap concat $ forM [1 .. ?n] $ \i -> do+    ((a, x), (abc', xs')) <- case splitAt (i - 1) $ zip abc xs of+        (ls, ax : rs) -> return (ax, unzip $ ls ++ rs)+        _             -> fail $+            "makeTupleAtInsts: no element at index " ++ show i++    let tupleAtInst :: Name -> Name -> Name -> Name -> DecQ+        tupleAtInst removeType removeData insertType insertData = instanceD+            (pure [])+            (foldl' appT (conT $ mkName "TupleAt") [+                litT $ numTyLit $ fromIntegral i,+                varT a,+                foldl' appT (conT removeType) $ map varT abc',+                foldl' appT (conT insertType) $ map varT abc])+            [+                funD (mkName "tupleInsert") [clause+                    [varP x, tildeP $ conP removeData $ map varP xs']+                    (normalB $ foldl' appE (conE insertData) $ map varE xs)+                    []],+                funD (mkName "tupleRemove") [clause+                    [conP insertData $ map varP xs]+                    (normalB $ tupE [+                        varE x,+                        foldl' appE (conE removeData) $ map varE xs'])+                    []]]++    sequence [+        {-+        instance TupleAt 1 b (a, c) (a, b, c) where+            tupleInsert x1 ~(x0, x2) = (x0, x1, x2)+            tupleRemove (x0, x1, x2) = (x1, (x0, x2))+        -}+        tupleAtInst+            (tupleTypeName $ ?n - 1)+            (tupleDataName $ ?n - 1)+            (tupleTypeName ?n)+            (tupleDataName ?n),++        -- TODO This tilde makes implementation simpler and probably has no+        -- impact, but let's confirm that with benchmarks.+        {-+        instance TupleAt 1 b (Pair a c) (StrictTuple3 a b c) where+            tupleInsert x1 ~(x0 :!: x2) = StrictTuple3 x0 x1 x2+            tupleRemove (StrictTuple3 x0 x1 x2) = (x1, x0 :!: x2)+        -}+        tupleAtInst+            (strictTName $ ?n - 1)+            (strictDName $ ?n - 1)+            (strictTName ?n)+            (strictDName ?n)]++makeStrictTupleAndInsts :: (?n :: Int) => DecsQ+makeStrictTupleAndInsts = do+    (x1, x2) <- case drop (?n - 2) xs of+        [x1, x2] -> return (x1, x2)+        _        -> fail "makeStrictTupleAndInsts: ?n < 2"++    {-+    data StrictTuple4 a b c = StrictTuple4 a b c+        deriving (...)+    -}+    strictTupleDef <- dataD+        (pure [])+        (strictTName ?n)+        [PlainTV a BndrReq | a <- abc]+        Nothing+        [normalC (strictDName ?n) $ map banged abc]+        [derivClause Nothing $ map conT [+            ''Eq,+            ''Ord,+            ''Read,+            ''Show,+            ''Foldable,+            ''Functor,+            ''Traversable,+            ''Generic,+            ''Generic1]]++    {-+    instance (Hashable a, Hashable b, Hashable c) => Hashable (StrictTuple3 a b c)+    -}+    hashableInst <- instanceD+        (cxt [[t| Hashable $(varT a) |] | a <- abc])+        [t| Hashable $strictTupleSatT |]+        []++    {-+    instance (Hashable a, Hashable b) => Hashable1 (StrictTuple3 a b)+    -}+    hashable1Inst <- instanceD+        (cxt [[t| Hashable $(varT a) |] | a <- init abc])+        [t| Hashable1 $(strictTupleUnsatT 1) |]+        []++    {-+    instance (Eq a, Eq b) => Eq1 (StrictTuple3 a b) where+        liftEq = liftEq2 (==)+    -}+    eq1Inst <- instanceD+        (cxt [[t| Eq $(varT a) |] | a <- init abc])+        [t| Eq1 $(strictTupleUnsatT 1) |]+        [funD 'liftEq [clause [] (normalB [| liftEq2 (==) |]) []]]++    {-+    instance (Eq a) => Eq2 (StrictTuple3 a) where+        liftEq2 f g (StrictTuple3 x0 x1 x2) (StrictTuple3 y0 y1 y2) =+            x0 == y0 && f x1 y1 && g x2 y2+    -}+    eq2Inst <- instanceD+        (cxt [[t| Eq $(varT a) |] | a <- dropLast 2 abc])+        [t| Eq2 $(strictTupleUnsatT 2) |]+        [funD 'liftEq2 [clause+            [varP fName, varP gName, strictTupleP xs, strictTupleP ys]+            (normalB $ foldr+                (\boolE r -> [| $boolE && $r |])+                [|+                    $(varE fName) $(varE x1) $(varE $ ys !! (?n - 2)) &&+                    $(varE gName) $(varE x2) $(varE $ ys !! (?n - 1)) |]+                (dropLast 2 $+                    zipWith (\x y -> [| $(varE x) == $(varE y) |]) xs ys))+            []]]++    {-+    instance (NFData a, NFData b, NFData c) => NFData (StrictTuple3 a b c)+    -}+    nfDataInst <- instanceD+        (cxt [[t| NFData $(varT a) |] | a <- abc])+        [t| NFData $strictTupleSatT |]+        []++    {-+    instance (NFData a, NFData b) => NFData1 (StrictTuple3 a b)+    -}+    nfData1Inst <- instanceD+        (cxt [[t| NFData $(varT a) |] | a <- init abc])+        [t| NFData1 $(strictTupleUnsatT 1) |]+        []++    {-+    instance (NFData a) => NFData2 (StrictTuple3 a) where+        liftRnf2 r s (StrictTuple3 x0 x1 x2) = x0 `seq` r x1 `seq` s x2+    -}+    nfData2Inst <- instanceD+        (cxt [[t| NFData $(varT a) |] | a <- dropLast 2 abc])+        [t| NFData2 $(strictTupleUnsatT 2) |]+        [funD 'liftRnf2 [clause+            [varP fName, varP gName, strictTupleP xs]+            (normalB $ foldr+                (\x r -> [| rnf $(varE x) `seq` $r |])+                [| $(varE fName) $(varE x1) `seq` $(varE gName) $(varE x2) |]+                (dropLast 2 xs))+            []]]++    {-+    instance (Binary a, Binary b, Binary c) => Binary (StrictTuple3 a b c) where+        put = put . toLazy+        get = toStrict <$> get+    -}+    binaryInst <- instanceD+        (cxt [[t| Binary $(varT a) |] | a <- abc])+        [t| Binary $strictTupleSatT |]+        [+            funD 'put [clause [] (normalB [| put . toLazy |]) []],+            funD 'get [clause [] (normalB [| toStrict <$> get |]) []]]++    {-+    instance (Monoid a, Monoid b) => Applicative (StrictTuple3 a b) where+        pure = StrictTuple3 mempty mempty+        StrictTuple3 x0 x1 x2 <*> StrictTuple3 y0 y1 y2 =+            StrictTuple (x0 <> y0) (x1 <> y1) (x2 y2)+    -}+    applicativeInst <- instanceD+        (cxt [[t| Monoid $(varT a) |] | a <- init abc])+        [t| Applicative $(strictTupleUnsatT 1) |]+        [+            funD 'pure [clause+                [varP $ last xs]+                (normalB $ foldl' appE (conE $ strictDName ?n) $+                    replicate (?n - 1) [| mempty |] ++ [varE $ last xs])+                []],+            funD '(<*>) [clause+                [strictTupleP xs, strictTupleP ys]+                (normalB $ foldl' appE (conE $ strictDName ?n) $+                    let mappendE x y = [| $(varE x) <> $(varE y) |]+                        mappendE's = init $ zipWith mappendE xs ys+                    in mappendE's ++ [varE (last xs) `appE` varE (last ys)])+                []]]++    {-+    instance (Monoid a, Monoid b) => Monad (StrictTuple3 a b) where+        StrictTuple3 x0 x1 x2 >>= f = StrictTuple3 (x0 <> y0) (x1 <> y1) y2 where+            StrictTuple3 y0 y1 y2 = f x2+    -}+    monadInst <- instanceD+        (cxt [[t| Monoid $(varT a) |] | a <- init abc])+        [t| Monad $(strictTupleUnsatT 1) |]+        [funD '(>>=) [clause+            [strictTupleP xs, varP fName]+            (normalB $ foldl' appE (conE $ strictDName ?n) $+                let mappendE x y = [| $(varE x) <> $(varE y) |]+                in init (zipWith mappendE xs ys) ++ [varE $ last ys])+            [valD+                (strictTupleP ys)+                (normalB $ varE fName `appE` varE (last xs))+                []]]]++    otherInsts <-+        let bifoldMapP = tildeP $ conP (strictDName ?n) $+                replicate (?n - 2) wildP ++ [varP x1, varP x2]+        in [d|+            {-+            instance Strict (a, b, c) (StrictTuple3 a b c) where+                toStrict (x0, x1, x2) = StrictTuple3 x0 x1 x2+                toLazy (StrictTuple3 x0 x1 x2) = (x0, x1, x2)+            -}+            instance Strict $lazyTupleSatT $strictTupleSatT where+                toStrict $(tupP $ map varP xs) = $strictTupleSatE+                toLazy $(strictTupleP xs) = $(tupE $ map varE xs)++            {-+            instance Swap (StrictTuple3 a) where+                swap (StrictTuple3 x0 x1 x2) = StrictTuple3 x0 x2 x1+            -}+            instance Swap $(strictTupleUnsatT 2) where+                swap $(strictTupleP xs) =+                    $(strictTupleUnsatE 2) $(varE x2) $(varE x1)++            {-+            instance Bifoldable (StrictTuple3 a) where+                bifoldMap f g ~(StrictTuple3 _ x1 x2) = f x1 <> g x2+            -}+            instance Bifoldable $(strictTupleUnsatT 2) where+                bifoldMap f g $bifoldMapP = f $(varE x1) <> g $(varE x2)++            {-+            instance Bifunctor (StrictTuple3 a) where+                bimap f g ~(StrictTuple3 x0 x1 x2) =+                    StrictTuple3 x0 (f x1) (g x2)+            -}+            instance Bifunctor $(strictTupleUnsatT 2) where+                bimap f g $(tildeP $ strictTupleP xs) =+                    $(strictTupleUnsatE 2) (f $(varE x1)) (g $(varE x2))++            {-+            instance Bitraversable (StrictTuple3 a) where+                bitraverse f g ~(StrictTuple3 x0 x1 x2) =+                    liftA2 (StrictTuple3 x0) (f x1) (g x2)+            -}+            instance Bitraversable $(strictTupleUnsatT 2) where+                bitraverse f g $(tildeP $ strictTupleP xs) =+                    $(strictTupleUnsatE 2) <$> f $(varE x1) <*> g $(varE x2)+            |]++    return $ strictTupleDef+        : hashableInst+        : hashable1Inst+        : eq1Inst+        : eq2Inst+        : nfDataInst+        : nfData1Inst+        : nfData2Inst+        : binaryInst+        : applicativeInst+        : monadInst+        : otherInsts
+ test/DocTest01.hs view
@@ -0,0 +1,26 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE TypeApplications #-}++module DocTest01 (main) where++import Data.Tuple.Classes (curryN', uncurryN')++-- Function wrapper that expects a unary function+printArgAndRun :: (Show a) => (a -> IO b) -> a -> IO b+printArgAndRun f x = do+    print x+    f x++-- But we have a ternary function+printTitleAndSum :: String -> Int -> Int -> IO ()+printTitleAndSum title i j = do+    putStrLn title+    print $ i + j++-- We can adapt them+printArgsTitleAndSum :: String -> Int -> Int -> IO ()+printArgsTitleAndSum =+    curryN' @3 $ printArgAndRun $ uncurryN' @3 printTitleAndSum++main :: IO ()+main = printArgsTitleAndSum "Important identity" 26885 15184
+ test/DocTest02.hs view
@@ -0,0 +1,13 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE TypeApplications #-}++module DocTest02 (main) where++import Data.Tuple.Classes (TupleAt(..))++consTuple :: (TupleAt 1 a t u) => a -> t -> u+consTuple = tupleInsert @1++main :: IO ()+main = print $ consTuple 'x' $ consTuple False ("sequitur", "quodlibet")
+ test/Spec.hs view
@@ -0,0 +1,39 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE GHC2021 #-}++module Main (main) where++import Control.Exception  (SomeException, catch, evaluate)+import Data.Tuple.Classes++import DocTest01 qualified+import DocTest02 qualified++main :: IO ()+main = do+    DocTest01.main+    DocTest02.main++    testUncurryNLaziness+    testTupleInsertLaziness++testUncurryNLaziness :: IO ()+testUncurryNLaziness = do+    let f _ _ _ _ = putStrLn "OK"+        test method = method f $ error "not lazy enough"++    test $ uncurryN  @4+    test $ uncurryN' @4++testTupleInsertLaziness :: IO ()+testTupleInsertLaziness = do+    let test x = (True <$ evaluate x) `catch` \(_ :: SomeException) ->+            return False++    lazyConverged <- test $+        ith @2 $ tupleInsert @2 () (undefined :: Solo Int)+    if lazyConverged then putStrLn "OK" else error "too strict"++    strictConverged <- test $+        ith @2 $ tupleInsert @2 () (undefined :: Identity Int)+    if strictConverged then error "not strict enough" else putStrLn "OK"
+ tuple-classes.cabal view
@@ -0,0 +1,66 @@+cabal-version: 1.12++-- This file has been generated from package.yaml by hpack version 0.39.6.+--+-- see: https://github.com/sol/hpack++name:           tuple-classes+version:        1.0.0+synopsis:       Working with n-ary tuples and functions; strict tuples+description:    Please see the README on Codeberg at <https://codeberg.org/sjshuck/tuple-classes#readme>+category:       data+homepage:       https://codeberg.org/sjshuck/tuple-classes#readme+bug-reports:    https://codeberg.org/sjshuck/tuple-classes/issues+author:         Steven Shuck+maintainer:     stevenjshuck@gmail.com+copyright:      2026 Steven Shuck+license:        Apache-2.0+license-file:   LICENSE+build-type:     Simple+extra-source-files:+    README.md+    CHANGELOG.md++source-repository head+  type: git+  location: https://codeberg.org/sjshuck/tuple-classes++library+  exposed-modules:+      Data.Tuple.Classes+  other-modules:+      Data.Tuple.Classes.TH+      Paths_tuple_classes+  hs-source-dirs:+      src+  ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints+  build-depends:+      assoc+    , base >=4.9 && <5+    , binary+    , deepseq+    , hashable+    , strict+    , template-haskell+  default-language: GHC2021++test-suite tuple-classes-test+  type: exitcode-stdio-1.0+  main-is: Spec.hs+  other-modules:+      DocTest01+      DocTest02+      Paths_tuple_classes+  hs-source-dirs:+      test+  ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints+  build-depends:+      assoc+    , base >=4.9 && <5+    , binary+    , deepseq+    , hashable+    , strict+    , template-haskell+    , tuple-classes+  default-language: Haskell2010