Uncurry for n-ary functions

后端 未结 2 1168
自闭症患者
自闭症患者 2021-01-06 02:32

I have a type level numbers

data Z   deriving Typeable
data S n deriving Typeable

and n-ary functions (code from fixed-vector package)

2条回答
  •  不思量自难忘°
    2021-01-06 03:15

    This required a bit of care in unwrapping/rewrapping the Fun newtype. I also exploited the DataKinds extension.

    {-# LANGUAGE DataKinds, KindSignatures, TypeFamilies, 
        MultiParamTypeClasses, ScopedTypeVariables, FlexibleInstances #-}
    {-# OPTIONS -Wall #-}
    
    -- | Type-level naturals.
    data Nat = Z | S Nat
    
    -- | Type family for n-ary functions.
    type family   Fn (n :: Nat) a b
    type instance Fn Z     a b = b
    type instance Fn (S n) a b = a -> Fn n a b
    
    -- | Addition.
    type family   Add (n :: Nat) (m :: Nat) :: Nat
    type instance Add Z          m = m
    type instance Add (S n)      m = S (Add n m)
    
    -- | Newtype wrapper which is used to make 'Fn' injective.
    newtype Fun n a b = Fun { unFun :: Fn n a b }
    
    class UncurryN (n :: Nat) (m :: Nat) a b where
        uncurryN :: Fun (Add n m) a b -> Fun n a (Fun m a b)
    
    instance UncurryN Z m a b where
        uncurryN g = Fun g
    
    instance UncurryN n m a b => UncurryN (S n) m a b where
        uncurryN g = Fun (\x -> unFun (uncurryN (Fun (unFun g x)) :: Fun n a (Fun m a b)))
    
    {- An expanded equivalent with more signatures:
    
    instance UncurryN n m a b => UncurryN (S n) m a b where
        uncurryN g = let f :: a -> Fn n a (Fun m a b)
                         f x = let h :: Fun (Add n m) a b
                                   h = Fun ((unFun g :: Fn (Add (S n) m) a b) x)
                               in unFun (uncurryN h :: Fun n a (Fun m a b))
                         in Fun f
    -}
    

提交回复
热议问题