【问题标题】:Haskell Data Declaration : Find sum of Leaves in a binary Tree [duplicate]Haskell数据声明:查找二叉树中的叶子总和[重复]
【发布时间】:2020-10-09 01:16:49
【问题描述】:

这是一棵二叉树,我正在尝试计算叶子的总和

             -1
            /   \
          -5     10
          / \   
        -4  30  
        / \
       13  17

给出了数据声明。

data Tree = TNode Int [ Tree ] | TLeaf Int 

这是我的代码

let t = TNode (-1) [TNode (-5)  [  TNode (-4) [ Tleaf 13, Tleaf 17] ,  Tleaf 30 ] ,Tleaf 10 ]

sumLeaves (Tleaf x)= x
sumLeaves (TNode x [tree])=  sum[sumLeaves tree]

当我运行程序 sumLeaves t 时,它表明函数 sumLeaves 中存在非穷举模式。我认为问题是程序无法计算,当有一个节点有两个叶子时,但我没有不知道如何解决。非常感谢您的帮助。

编辑: 测试1:

 sumLeaves1 (Tleaf x)= [x]
    sumLeaves1 (TNode x [Tleaf y])=[y]
    sumLeaves1 (TNode x (y:ys))= sum ( (sumLeaves1 y) ++ (sumLeaves1 (TNode x ys)) )

测试 2:

 sumLeaves (Tleaf x)= x
    sumLeaves (TNode x [Tleaf y])=y
    sumLeaves (TNode x (y:ys))= (sumLeaves y) + sumLeaves (TNode x ys)

测试 2 工作正常,但测试 1 给出错误,当我删除 sum() 时,它给出了一个列表 [13,17,30,10] ,这是正确的列表,但是 >sum ( [13,17 ,30,10]) 在程序中工作。我该如何克服它?

【问题讨论】:

  • 您正在寻找的答案是重复的this one

标签: haskell binary-tree non-exhaustive-patterns


【解决方案1】:

您的(Tnode x [tree]) 仅在节点具有完全 一个子树时才匹配。你应该匹配 sublistlist 的任何值,所以:

sumLeaves :: Tree -> Int
sumLeaves (Tleaf x) = x
sumLeaves (TNode x trees) = sum (…)

这里 应该创建一个节点子节点总和的列表。因此,您应该为trees 中的每个元素进行映射。我把它留作练习。你可能想看看map :: (a -> b) -> [a] -> [b]

话虽如此,您不必自己对元素求和。您可以提升 Tree 数据类型并利用 DeriveFoldable extension 让 Haskell 为您派生一个 Foldable 实例:

{-# LANGUAGE DeriveFoldable #-}

data Tree a = TNode a [ Tree a ] | TLeaf a deriving Foldable

sum :: (Foldable f, Num a) => f a -> a 定义在任何Foldable 上,因此我们可以总结为:

Prelude> sum (TNode (-1) [TNode (-5)  [  TNode (-4) [ TLeaf 13, TLeaf 17] ,  TLeaf 30 ] ,TLeaf 10 ])
60

【讨论】:

  • 我对 DeriveFoldable 扩展感到困惑,没有它可以解决问题吗?
  • @JohnTang:是的,第一部分描述了问题所在,... 留作练习。
  • 我有一个问题,是 sum(..) 还是 sum[..],因为当我输入 >sum (1,4) 时,它会给出 4 ,这真的很令人困惑,但是 sum [ 1,4] 工作正常。
  • @JohnTang: 那是因为你使用的是一个元组,因此你使用了一个 2 元组的 Foldable 实例,但是代码中的 (...) 应该生成 i> 一个列表。但是,如果您使用 [ x ],您将创建一个 singleton 列表,该列表包含一个元素。所以你应该简单地寻找一个生成列表的表达式。
猜你喜欢
  • 2019-11-21
  • 2016-01-24
  • 2021-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多