如何测量 Haskell 中 MultTree 的大小?

How to measure the size of a MultTree in Haskell?

我对 Haskell 很陌生,因此不是很熟悉。

下面的方法是测量一个MultTree的尺寸。

一个 MultTree 包含 Index 个节点,其中包含两个 Int,并且可以有任意数量的子节点。然后还有 Data 个包含一个 Int 并且不能有子节点的节点。那么这个方法应该判断的是,最长的'branch'是多长

我目前的方法:

data MultTree a = Index a a [MultTree a] | Data a deriving Show

size :: MultTree a -> Int
size (Index a b []) = 1
size (Index a b [Index c d [e]]) = size (Index c d [e]) + 1

它确实可以编译,但是在尝试使用它时,我得到 "non-exhaustive patterns in function size"。即使我不会收到该错误,我也知道它不会按照我希望的方式工作。

但不知为何我想不出解决问题的方法。

我将不胜感激。

提前谢谢你!

你写:

"So what the method should determine is, how long the longest 'branch' is."

不是“大小”,通常叫“深度”:

depth :: MultTree a -> Int

那么我们有什么? a 是值,存在于 Index 个分支节点或 Data 个叶节点中:

data MultTree a = Index a a [MultTree a] 
                | Data a 
                deriving Show

depth (Data a)          = 0   -- or 1, whatever you prefer
depth (Index _ _ trees) = 

好吧,我们对这些值本身没有用,至于树,只要我们能找到每一个树的深度,我们就能找到最大值,

    let max_depth = maximum [ find_depth t | t <- trees ]
    in
        max_depth + 1

现在开始编写 find_depth 函数。它所需的类型取决于我们如何使用它,是 find_depth :: MultTree a -> Int。嗯,

(其余故意留空)




哦,错误的原因是,[e] as a type stands for "a list of e-类型值";但是 作为一种模式 ,它代表“ 一个值 的单例列表”——当该列表中有多个值时,例如案例未涵盖,因此出现“非详尽模式”错误,即需要更多模式来涵盖这些案例,但它们缺失了。

类似地,[Index c d [e]] 作为模式 代表“一个的单例列表,类型为MultTree a,它匹配模式 Index c d [e],其中 cd 都是 a 类型的值,而 [e] 是一个值的单例列表由 MultTree a 类型确定的类型——即再次 MultTree a:

data MultTree a = Index a a [MultTree a] 
                | ...