【问题标题】:Haskell Tree to List - preorder traversalHaskell Tree to List - 前序遍历
【发布时间】:2012-02-29 00:50:15
【问题描述】:

给定 Haskell 中的以下树结构:

data Tree = Leaf Int | Node Int Tree Tree deriving Show

如何让 Haskell 返回预购数据列表?

例如给定一棵树:

Node 1 (Leaf 2) (Leaf 3)

返回类似:

preorder = [1,2,3]

【问题讨论】:

  • 满意后别忘了接受答案。

标签: haskell tree tree-traversal


【解决方案1】:

您可以寻求更通用的解决方案,并将您的数据类型设为Foldable 的实例。 hackage 有一个非常相似的示例,但它实现了订单后访问。 如果您想支持预购访问,您必须编写如下内容:

import qualified Data.Foldable as F

data Tree a = Leaf a | Node a (Tree a) (Tree a) deriving Show

instance F.Foldable Tree where
    foldr f z (Leaf x) = f x z
    foldr f z (Node k l r) = f k (F.foldr f (F.foldr f z r) l)

有了这个,你就可以使用在Foldable类型上工作的每个函数,比如elemfoldrfoldrsumminimummaximum等等(参考here)。

特别是,您正在搜索的列表可以通过toList 获得。以下是您可以通过该实例声明编写的一些示例:

*Main> let t = Node 1 (Node 2 (Leaf 3) (Leaf 4)) (Leaf 5)
*Main> F.toList t
[1,2,3,4,5]
*Main> F.foldl (\a x -> a ++ [x]) [] t
[1,2,3,4,5]
*Main> F.foldr (\x a -> a ++ [x]) [] t
[5,4,3,2,1]
*Main> F.sum t
15
*Main> F.elem 3 t
True
*Main> F.elem 12 t
False

【讨论】:

    【解决方案2】:

    使用模式匹配

    preorder (Leaf n) = [n]
    preorder (Node n a b) = n:(preorder a) ++ (preorder b)
    

    【讨论】:

    • 我收到以下错误:无法匹配预期类型 [t0]' with actual type Tree' 在模式中:节点 nab 在“预购”预购(节点 nab)= n 的方程式中:(预购 a) ++(预购b)
    • @Gravy 这很奇怪。尝试添加显式类型签名preorder :: Tree -> [Int]。对我来说你会出错是没有意义的。
    • 这很奇怪,我刚刚对其进行了测试,似乎可以正常工作。您确定所有内容都正确复制了吗?
    • @Gravy 还要确保你有preorder (Leaf n) = [n] 而不是preorder (Lead n) = n。那些[ ] 很重要。
    • preorder(Leaf n) = [n] preorder(Node n treeL treeR) = [n] ++ preorder treeL ++ preorder treeR
    【解决方案3】:

    好的,很抱歉回复晚了,但我的工作如下:

    preorder(Leaf n) = [n]
    preorder(Node n treeL treeR) = [n] ++ preorder treeL ++ preorder treeR'code'
    

    但这对我仍然不起作用

    preorder (Leaf n) = [n]   
    preorder (Node n a b) = n:(preorder a) ++ (preorder b) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-30
      • 2017-09-16
      • 2011-11-25
      • 1970-01-01
      相关资源
      最近更新 更多