我想在库中做一些魔术,允许多态地解构产品类型。这是一个或多或少的工作模型,说明了我想做的事情:
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, UndecidableInstances #-}
newtype Wrapped a = Wrapped { unwrap :: a }
-- our example structure
ex :: (Int, (Int, Int))
ex = (1,(2,3))
class WrapDecomp x y | y -> x where
decomp :: x -> y
instance (WrapDecomp x x', WrapDecomp y y')=> WrapDecomp (x,y) (x',y') where
decomp (x,y) = (decomp x, decomp y)
instance WrapDecomp x (Wrapped x) where
decomp = Wrapped
example = let w = decomp ex
(w0, w1) = decomp ex
(w0', (w1', w2')) = decomp ex :: (Wrapped Int, (Wrapped Int, Wrapped Int))
in print $ ( unwrap w, unwrap w0, unwrap $ snd w1, unwrap $ fst w1 )
-- Also works:
-- in print $ ( unwrap w, unwrap w0, unwrap w1 )
我的实际应用程序是一个库,并且将具有两个属性,使我在上面注意到的疣可以接受:
Wrapped
类型构造函数未导出用户将始终调用绑定中的
unwrap
所有Wrapped
数据(因为我的应用程序的细节很无聊),所以在实践中不应该有歧义
共识似乎UndecidableInstances
还不错,但我想在继续之前确定以上内容是否符合犹太教规。
更新/解决方案
我对此感到困惑,但我能够通过以下方式解决我的问题TypeFamilies
:
{-# LANGUAGE TypeFamilies #-}
class Out a where
type In a :: *
decomp :: In a -> a
instance Out (Wrapped a) where
type In (Wrapped a) = a
decomp = Wrapped
instance (Out a, Out b)=> Out (a,b) where
type In (a,b) = (In a,In b)
decomp (x,y) = (decomp x, decomp y)