简体   繁体   English

将树缩减为haskell中的列表

[英]Reducing Tree to a list in haskell

I am trying to reduce a Tree to List but I am stuck up here.. any suggestions are appreciated.. 我正在尝试将树减少到列表,但我被困在这里..任何建议都赞赏..

data Tree a = Leaf a | Node (Tree a) a (Tree a) deriving (Eq, Show)
treeToList :: (Ord a) => Tree a -> [a]
treeToList (Node root left right) = treeToList left ++ [root] ++   treeToList right

Expecting Result: 期待结果:

 ghci> treeToList (Node (Leaf 1) 2 (Node (Leaf 3) 4 (Leaf 5))) [1,2,3,4,5] 

You have two errors: 你有两个错误:

  1. Non-exhaustive pattern (for Leaf constructor). 非详尽模式(对于Leaf构造函数)。
  2. And in the pattern for Node you matching root as a left tree value ( Tree a ) and not an a . Node的模式中,您将root匹配为左树值( Tree a )而不是a

Thus the result should look like: 因此结果应如下所示:

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

treeToList :: (Ord a) => Tree a -> [a]
treeToList (Leaf v) = [v]
treeToList (Node left root right) = treeToList left ++ [root] ++ treeToList right
 *Main> treeToList (Node (Leaf 1) 2 (Node (Leaf 3) 4 (Leaf 5))) [1,2,3,4,5] 

Riffing on m0nhawk's absolutely correct answer, I'd offer the following advice. 关于m0nhawk的绝对正确答案,我会提供以下建议。 When you're writing a function that pattern matches on an algebraic data type like Tree , start by writing a template of how the function will be structured. 当您编写一个函数,模式匹配代数数据类型如Tree ,首先编写一个函数将如何构造的模板。 In this case, given the type definition: 在这种情况下,给定类型定义:

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

...and this function signature: ...和这个功能签名:

treeToList :: (Ord a) => Tree a -> [a]

...you can start by writing a template like this one, which is just expanding out the two alternatives of the Tree type and their components: ...你可以从编写像这样的模板开始,这只是扩展Tree类型及其组件的两个选择:

treeToList (Leaf value) = _
treeToList (Node left value right) = _

Read the _ (underscores) as "blanks" to fill in later. _ (下划线)读作“空白”以便稍后填写。 This is actually valid syntax in recent GHC versions, called a "hole" so the compiler will remind you that you need to fill it in. 这实际上是最近GHC版本中的有效语法,称为“漏洞”,因此编译器会提醒您需要填写它。

By writing out a template like this and making sure you're covering all of the alternatives of the type you're working with, you greatly reduce your risk of running into problem #1 that m0nhawk pointed out. 通过写出这样的模板并确保覆盖所有类型的替代方案,您可以大大降低遇到m0nhawk指出的问题#1的风险。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM