Haskell中树数据结构的邻接列表

时间:2014-07-10 23:49:38

标签: haskell

我在Haskell中定义了以下抽象数据类型:

data Trie = Leaf
          | Node [(Char, Trie)]
          deriving (Eq)

Node类型是元素(c, t)的列表,其中c是从当前节点到t的边的标签。

现在我要打印出树的邻接列表。具体来说,我需要每行打印一个边,其中边的格式为:

  

n1 n2 c

来源为n1,目标为n2,边缘为c

我可以用

打印我的根节点的边缘
instance Show Trie where
    show = show' 2 1
        where show' _ _ Leaf = ""
              show' next n1 (Node ts) = unlines $ zipWith (\n2 (c, _) ->
                                                           show n1 ++ " " ++ show n2 ++ " " ++ show c)
                                                    [next..] ts

但现在我被困在如何以递归方式打印孩子们。特别是,如何为子节点编号?

3 个答案:

答案 0 :(得分:5)

标记节点非常简单,因为GHC将为您完成所有繁重工作:

{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-}

import qualified Data.Traversable as T
import qualified Data.Foldable as F 
import Control.Monad.State 

data Trie a = Leaf a | Node a [(Char, Trie a)] 
  deriving (Eq, Functor, F.Foldable, T.Traversable)

number :: Trie a -> Trie (a, Int)
number = flip evalState 1 . T.mapM (\x -> state $ \n -> ((x,n),n+1))

至于打印特里,我担心我不太了解所需的输出。

答案 1 :(得分:4)

我提出了这个解决方案:

import Data.List (foldl')

enum :: Int -> Trie -> ([(Int,Int,Char)],Int)
enum x Leaf = ([],x+1)
enum x (Node pairs)
  = let go (acc,y) (c,t) = (acc',y')
          where acc' = [(x,y,c)] ++ edges ++ acc
                (edges,y') = enum y t
    in foldl' go ([],x+1) pairs

enum获取起始ID和Trie并返回边缘列表和下一个可用ID。

-- some examples:

leafs xs = [ (c,Leaf) | c <- xs ]
t1 = Node $ leafs "XYZ"
t2 = Node [('W', t1)]
t3 = Node $ [('A',t2)] ++ leafs "BC"

enum 1 t1 -- ([(1,4,'Z'),(1,3,'Y'),(1,2,'X')],5)
enum 1 t2 -- ([(1,2,'W'),(2,5,'Z'),(2,4,'Y'),(2,3,'X')],6)
enum 1 t3 -- ([(1,8,'C'),(1,7,'B'),(1,2,'A'),(2,3,'W'),(3,6,'Z'),(3,5,'Y'),(3,4,'X')],9)

答案 2 :(得分:0)

这是我的尝试:

data Trie c =
    Leaf
  | Node [(c, Trie c)]
  deriving (Eq)

instance Show c => Show (Trie c) where
  show = show' 1 (\_ -> "\n") where
      show' next cc Leaf = show next ++ "\n” ++ cc (next + 1)
      show' next cc (Node []) = show next ++ "\n” ++ cc (next + 1)
      show' next cc (Node [(c,t)] = show c ++ "(" ++ show next ++ ")” ++ show' (next+1) cc t
      show' next cc (Node (x:xs)) = show' next (\n -> show' n cc $ Node xs) (Node [x])

我使用延续传递方式来跟踪状态。应该有一种方法可以使代码成为monadic,或者使用拉链。

您可以更改叶子或节点的特定位,具体取决于您是否需要编号(通过更改next + 1部分)。