如何解决haskell树问题

如何解决haskell树问题,haskell,tree,Haskell,Tree,谁能帮我解决这个问题。我是哈斯克尔的新手,对这个问题一无所知 考虑以下数据类型 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

谁能帮我解决这个问题。我是哈斯克尔的新手,对这个问题一无所知

考虑以下数据类型

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]
请注意,数据类型
可以存储不同类型的值
在叶子上比在分支节点上。因此,这些
函数采用两个函数作为参数:第一个函数映射
将存储在叶子中的值转换为某个常见类型
c
,以及 第二个函数将存储在分支节点中的值映射到类型
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

您提供的代码看起来是正确的。为了测试,这里有一个漂亮的小例子:

此树的表示形式可能如下所示:

tree :: Tree Int Int
tree = Branch 1 (Branch 2 (Leaf 4) (Leaf 5)) (Leaf 3)
这里的叶子和内部节点都是
Int
类型

现在,
preorder
inoorder
函数分别具有两个类型为
(a->c)
(b->c)
的附加函数
f
g
,以下是将树叶中的数据从类型
a
转换为某种类型
c
的方法,以及将内部分支中的数据从类型
b
转换为类型
c
的方法。这是您必须自己提供的两个功能,具体取决于所需的输出类型
c

例如,让我们考虑一个完整的例子:<代码>树INTING String < /C>。我们传入两个函数

intToStr
strotstr
,作为将叶子和内部节点的数据转换为所需输出类型的方法:
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 :("

到目前为止你试过什么?你在哪里遇到问题?前序::(a->c)->(b->c)->树a b->[c]前序f g(叶x)=[f x]前序f g(分支x l r)=g x:(前序f g l++前序f g r)顺序::(a->c)->(b->c)->树a b->[c]前序f g(叶x)=[f x]前序f g(分支x l r)=前序f g l++[g x]++因为我不知道如何检验我的答案看起来是否正确。你试过测试什么?它在哪些方面给你带来了麻烦?请准确地提供您尝试过的内容以及您收到的任何错误消息的全文。我只是不知道如何测试它是否正确。我应该在函数中输入哪些参数来测试它?