折叠递归型系列

时间:2014-06-16 21:44:07

标签: haskell type-families data-kinds

我试图用虚拟类型[*]折叠数据。这是我的代码的简化版本

{-# LANGUAGE DataKinds, KindSignatures #-}

module Stack where
import Data.HList
import Data.Foldable as F

data T (a :: [*]) = T (Tagged a String)
(!++!) :: T a -> T b -> T (HAppendList a b)
(T a) !++! (T b) = T (Tagged (untag a ++ untag b))


a = T (Tagged "1") :: T '[Int]
b = T (Tagged "-- ") :: T '[]
ab = a !++! b :: T '[Int]

我想要一个折叠算子

(!++*) :: (Foldable t ) =>  T a -> t (T '[]) -> T a
a !++* t = F.foldl (!++!) a t

但这并不奏效。 aHAppendList a '[]不同的编译器,即使它们不是。

为什么编译统一HAppendList a '[]a

(我无法通过:t a !++! b !++! b !++! b => T '[Int]

手动在ghci中进行折叠

1 个答案:

答案 0 :(得分:5)

请注意HAppendList的定义:

type family HAppendList (l1 :: [k]) (l2 :: [k]) :: [k]
type instance HAppendList '[] l = l
type instance HAppendList (e ': l) l' = e ': HAppendList l l'

您和我知道[]++的左右标识,但编译器只知道左侧标识:

happend' :: T a -> T b -> T (HAppendList a b)
happend' (T (Tagged a)) (T (Tagged b)) = (T (Tagged (a++b)))

-- Doesn't typecheck 
leftIdentity' :: T a -> T '[] -> T a 
leftIdentity' x y = happend' x y 

rightIdentity' :: T '[] -> T a -> T a 
rightIdentity' x y = happend' x y 

你需要

type instance HAppendList '[] l = l
type instance HAppendList l '[] = l
type instance HAppendList (e ': l) l' = e ': HAppendList l l'

让编译器知道左右身份;但这些会重叠,所以它不会打字。然而,你可以翻开辩论:

(!+++!) :: T a -> T b -> T (HAppendList a b) 
(!+++!) (T (Tagged x)) (T (Tagged y)) = T (Tagged (y ++ x))

(!++*) :: Foldable t => T a -> t (T '[]) -> T a
a !++* t = F.foldl (flip (!+++!)) a t

在ghc 7.8中引入封闭类型系列,您可以解决此问题:

type family (++) (a :: [k]) (b :: [k]) :: [k] where 
  '[] ++ x = x
  x ++ '[] = x
  (x ': xs) ++ ys = x ': (xs ++ ys)

happend :: T a -> T b -> T (a ++ b)
happend (T (Tagged a)) (T (Tagged b)) = (T (Tagged (a++b)))

leftIdentity :: T a -> T '[] -> T a 
leftIdentity x y = happend x y 

rightIdentity :: T '[] -> T a -> T a 
rightIdentity x y = happend x y