4

我有一个类似 Set 的数据结构,实现为 Trie,其定义如下:

import qualified Data.Map as M
import Data.Foldable (Foldable, foldr)
import Prelude hiding (foldr)
import Data.Maybe (fromMaybe)

data Trie a = Trie { endHere :: Bool 
                   , getTrie :: M.Map a (Trie a)
                   } deriving (Eq)

还有一个如下所示的插入操作:

insert :: (Ord a, Foldable f) => f a -> Trie a -> Trie a
insert = foldr f (\(Trie _ m) -> Trie True m) where
  f e a = overMap (M.alter (Just . a . fromMaybe (Trie False M.empty)) e)

overMap :: Ord b => (M.Map a (Trie a) -> M.Map b (Trie b)) -> Trie a -> Trie b
overMap f (Trie e m) = Trie e (f m)

我可以得到一种foldr看起来像这样的东西:

foldrTrie :: ([a] -> b -> b) -> b -> Trie a -> b
foldrTrie f i (Trie a m) = M.foldrWithKey ff s m where
  s    = if a then f [] i else i
  ff k = flip (foldrTrie $ f . (k :))

但我无法弄清楚Foldable. Trie似乎具有所有必要的foldrTrie功能,但我只是无法弄清楚类型。

foldr这是我正在寻找的行为示例:

fromList :: (Ord a, Foldable f, Foldable g) => f (g a) -> Trie a
fromList = foldr insert (Trie False M.empty)

toList :: (Ord a) => Trie a -> [[a]]
toList = foldr (:) [] -- replace foldr here with foldrTrie and you'll get the 
                      -- desired behaviour

toList (fromList ["abc", "def"]) -- ["abc","def"]

我无法管理的是类型签名Foldable

instance Foldable Trie a where

我试着让我Trie有第二个类型参数:

data Trie a (f a) = Trie { endHere :: Bool
                         , getTrie :: M.Map a (Trie a (f a))
                         } deriving (Eq)

这样我就可以做这样的事情:

instance Foldable Trie a f where
  foldr f i (Trie a m) = M.foldrWithKey ff s m where
    s    = if a then f [] i else i
    ff k = flip (foldrTrie $ f . (k :))

但我无法弄清楚类型。

提出问题的更一般的方法可能是这样的:如果我有一个只能存储列表的数据结构我是否能够foldr在该数据结构上进行定义,因此它将存储的列表视为每个元素?该数据结构的类型是什么样的?

4

1 回答 1

5

这可能不是您想要做的,但是您可以将通用数据结构包装到 GADT 中,它只允许将列表存储在叶子上。为简单起见,使用树而不是 Tries 的简单示例:假设通用数据结构是Tree,并且我们要使其LTree仅允许列表树:

{-# LANGUAGE GADTs #-}

import Prelude hiding (foldr)
import Data.Foldable
import Data.Tree

foldrForListTrees :: ([a] -> b -> b) -> b -> Tree [a] -> b
foldrForListTrees = error "This is the one you are supposed to be able to write"

data LTree a where
    MkLTree :: Tree [a] -> LTree [a]

instance Foldable LTree where
    foldr f ys0 (MkLTree xs) = foldrForListTrees f ys0 xs
于 2015-11-02T03:41:05.010 回答