标准解决方案是创建一个存在量化的数据类型。结果将类似于
{-# LANGUAGE ExistentialQuantification #-}
data Exists1 = forall a . (Show a) => Exists1 a
instance Show Exists1 where
showsPrec _ (Exists1 x) = shows x
somethingPrintable1 :: Int -> Exists1
somethingPrintable1 x = Exists1 x
现在,可以自由地使用
show (somethingPrintable 42)
。我猜
Exists1
不能是
newtype
,这是因为需要在隐藏的上下文字典中传递特定的
show
实现。对于类型安全的向量,可以采用同样的方法创建
fromList1
实现:
{-# LANGUAGE GADTs #-}
data Zero
data Succ n
data Vec a n where
Nil :: Vec a Zero
Cons :: a -> Vec a n -> Vec a (Succ n)
data Exists1 f where
Exists1 :: f a -> Exists1 f
fromList1 :: [a] -> Exists1 (Vec a)
fromList1 [] = Exists1 Nil
fromList1 (x:xs) = case fromList1 xs of
Exists1 r -> Exists1 $ Cons x r
这个方法运行良好,但我认为主要缺点是需要额外的构造器。每次调用
fromList1
都会产生一个构造器的应用,然后立即解构。与之前一样,
Exists1
不能使用
newtype
,但我猜想,在没有任何类型类限制的情况下,编译器可以允许它。
我基于 rank-N continuation 创建了另一种解决方案。它不需要额外的构造器,但我不确定是否额外的函数应用会增加类似的开销。在第一种情况下,解决方案如下:
{-# LANGUAGE Rank2Types #-}
somethingPrintable2 :: Int -> ((forall a . (Show a) => a -> r) -> r)
somethingPrintable2 x = \c -> c x
现在,要获取结果,人们会使用 somethingPrintable 42 show
。
而对于 Vec
数据类型:
{-# LANGUAGE RankNTypes, GADTs #-}
fromList2 :: [a] -> ((forall n . Vec a n -> r) -> r)
fromList2 [] c = c Nil
fromList2 (x:xs) c = fromList2 xs (c . Cons x)
newtype Exists3 f r = Exists3 { unexists3 :: ((forall a . f a -> r) -> r) }
fromList3 :: [a] -> Exists3 (Vec a) r
fromList3 [] = Exists3 (\c -> c Nil)
fromList3 (x:xs) = Exists3 (\c -> unexists3 (fromList3 xs) (c . Cons x))
使用几个辅助函数可以使这段代码更易读:
exists3 :: f x -> Exists3 f r
exists3 x = Exists3 (\c -> c x)
{-# INLINE exists3 #-}
(?$) :: (forall a . f a -> r) -> Exists3 f r -> r
(?$) f x = unexists3 x f
{-# INLINE (?$) #-}
fromList3 :: [a] -> Exists3 (Vec a) r
fromList3 [] = exists3 Nil
fromList3 (x:xs) = (exists3 . Cons x) ?$ fromList3 xs
我看到这里的主要缺点有:
- 可能会带来额外的函数应用开销(我不知道编译器可以优化多少)。
- 代码可读性减少(至少对于不习惯continuations的人来说)。