如何解决haskell树prorder

时间:2017-06-21 05:20:47

标签: haskell tree

任何人都可以帮我解决问题。我是haskell的新手,并不知道这个问题。

  

考虑以下数据类型。

data Tree a b = Branch b (Tree a b) (Tree a b)
              | Leaf a
     

问题7.(10分)实现以给定顺序遍历树的两个函数从树节点收集值   列表:

preorder :: (a -> c) -> (b -> c) -> Tree a b -> [c]
inorder  :: (a -> c) -> (b -> c) -> Tree a b -> [c]
     

请注意,数据类型Tree可以存储不同类型的值   在叶子中而不是在分支节点上。因此,这些中的每一个   函数有两个函数作为参数:第一个函数映射   叶子中存储的值为某些常见类型c,以及   第二个函数将存储在分支节点中的值映射到type   因此,c生成了[c]类型的列表。

到目前为止,我已经尝试了以下内容,但不知道如何测试我的答案:

preorder :: (a -> c) -> (b -> c) -> Tree a b -> [c] 
preorder f g (Leaf x)= [f x] 
preorder f g (Branch x l r) = g x : (preorder f g l ++ preorder f g r) 

inorder :: (a -> c) -> (b -> c) -> Tree a b -> [c] 
inorder f g (Leaf x) = [f x] 
inorder f g (Branch x l r) = inorder f g l ++ [g x] ++ inorder f g r

1 个答案:

答案 0 :(得分:0)

您提供的代码看起来是正确的。为了测试,这里有一个漂亮的小例子: http://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/

这棵树的表示可能是这样的:

tree :: Tree Int Int
tree = Branch 1 (Branch 2 (Leaf 4) (Leaf 5)) (Leaf 3)

此处叶子和内部节点都是Int类型。

现在,preorderinorder函数分别使用fg两个类型(a -> c)(b -> c)的附加函数将叶片中的数据从类型a转换为某种类型c,将内部分支中的数据从类型b转换为c。这些是您必须自己提供的两个功能,具体取决于您所需的输出类型c

例如,让我们考虑Tree Int String的完整示例。我们传递了两个函数intToStrstrToStr作为转换树叶和内部节点的方法。数据到我们想要的输出类型:String

 data Tree a b = Branch b (Tree a b) (Tree a b)
               | Leaf a

 tree :: Tree Int String
 tree = Branch "one" (Branch "two" (Leaf 4) (Leaf 5)) (Leaf 3)

 preorder :: (a -> c) -> (b -> c) -> Tree a b -> [c] 
 preorder f g (Leaf x)= [f x] 
 preorder f g (Branch x l r) = g x : (preorder f g l ++ preorder f g r) 

 inorder :: (a -> c) -> (b -> c) -> Tree a b -> [c] 
 inorder f g (Leaf x) = [f x]
 inorder f g (Branch x l r) = inorder f g l ++ [g x] ++ inorder f g r

 strToStr :: String -> String
 strToStr s = s

 intToStr :: Int -> String
 intToStr i = show i

 main = do
     if (preorder intToStr strToStr tree == ["one", "two", "4", "5", "3"]) &&
        (inorder intToStr strToStr tree  == ["4", "two", "5", "one", "3"])
         then putStrLn "Correct implementation!"
         else putStrLn "Something went wrong :("