为什么差异列表不是可折叠的实例?

时间:2013-03-23 17:03:20

标签: haskell church-encoding difference-lists

dlist package包含DList数据类型,其中包含大量实例,但不包含FoldableTraversable。在我看来,这是两个最“类似列表”的类型。是否存在DList不是这些类的实例的性能原因?

此外,该软件包确实实现了foldrunfoldr,但没有实现其他折叠功能。

2 个答案:

答案 0 :(得分:22)

您应该考虑使用教会编码列表而不是DList。我们的想法是,您将列表表示为一个不透明的值,该值知道如何在列表上执行foldr。这需要使用RankNTypes扩展程序:

{-# LANGUAGE RankNTypes #-}

import Prelude 
import Control.Applicative
import Data.Foldable (Foldable)
import qualified Data.Foldable as F
import Data.Traversable (Traversable)
import qualified Data.Traversable as T

-- | Laws:
--
-- > runList xs cons nil == xs
-- > runList (fromList xs) f z == foldr f z xs
-- > foldr f z (toList xs) == runList xs f z
newtype ChurchList a = 
    ChurchList { runList :: forall r. (a -> r -> r) -> r -> r }

-- | Make a 'ChurchList' out of a regular list.
fromList :: [a] -> ChurchList a
fromList xs = ChurchList $ \k z -> foldr k z xs

-- | Turn a 'ChurchList' into a regular list.
toList :: ChurchList a -> [a]
toList xs = runList xs (:) []

-- | We can construct an empty 'ChurchList' without using a @[]@.
nil :: ChurchList a 
nil = ChurchList $ \_ z -> z

-- | The 'ChurchList' counterpart to '(:)'.  Unlike 'DList', whose
-- implementation uses the regular list type, 'ChurchList' doesn't
-- rely on it at all.
cons :: a -> ChurchList a -> ChurchList a
cons x xs = ChurchList $ \k z -> k x (runList xs k z)

-- | Append two 'ChurchList's.  This runs in O(1) time.  Note that
-- there is no need to materialize the lists as @[a]@.
append :: ChurchList a -> ChurchList a -> ChurchList a
append xs ys = ChurchList $ \k z -> runList xs k (runList ys k z)

-- | Map over a 'ChurchList'.  No need to materialize the list.
instance Functor ChurchList where
    fmap f xs = ChurchList $ \k z -> runList xs (\x xs' -> k (f x) xs') z

-- | The 'Foldable' instance is trivial, given the 'ChurchList' law.
instance Foldable ChurchList where
    foldr f z xs = runList xs f z

instance Traversable ChurchList where
    traverse f xs = runList xs step (pure nil)
        where step x rest = cons <$> f x <*> rest

这样做的缺点是tail没有有效的ChurchList操作 - 折叠ChurchList很便宜,但重复尾巴很费力......

答案 1 :(得分:12)

DList a是围绕[a] -> [a]的新类型包装器,其在逆变位置具有a,因此无法实现FoldableTraversable,甚至Functor直接。实现它们的唯一方法是转换为常规列表(参见foldr实现),这会破坏差异列表的性能优势。