【问题标题】:How to measure the size of a MultTree in Haskell?如何在 Haskell 中测量 MultTree 的大小?
【发布时间】:2021-04-27 16:58:32
【问题描述】:

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

下面的方法是测量一个MultTree的大小。

MultTree 包括 Index 节点,其中包含两个 Int 并且可以有任意数量的子节点。然后还有Data 节点包含一个Int 并且不能有子节点。那么方法应该确定的是,最长的“分支”有多长。

到目前为止我的方法:

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"。即使我不会收到那个错误,我也知道它不会按照我想要的方式工作。

但不知何故,我无法想出解决问题的办法。

我将不胜感激。

提前谢谢你!

【问题讨论】:

    标签: haskell recursion tree algebraic-data-types non-exhaustive-patterns


    【解决方案1】:

    你写:

    “那么方法应该确定的是,最长的‘分支’有多长。”

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

    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 -&gt; Int。嗯,

    (其余部分故意留空)




    哦,错误的原因是,[e]as a type 代表“a list of e-type values”;但作为一种模式,它代表“一个值的单例列表”——当该列表中有多个值时,不包括这种情况,因此“非详尽模式”错误,即需要更多模式来涵盖这些情况,但它们缺失了。

    类似地,[Index c d [e]] 作为一个模式 代表“一个 的单例列表,类型为 MultTree a,它与模式 Index c d [e] 匹配,其中两者cda 类型的值,[e] 是由 MultTree a 类型确定的类型的一个值的单例列表 - 即再次,MultTree a

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-18
      • 1970-01-01
      • 2014-10-07
      • 1970-01-01
      • 2011-04-19
      • 1970-01-01
      • 2023-02-21
      相关资源
      最近更新 更多