Haskell: leafCount 函数使用 fold fun 获取 Tree 输出 Int

Haskell: leafCount function take Tree output Int using fold fun

我将树类型定义为:

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

这里有一个折叠功能:,和我用的基本一样

现在我想写一个函数 leafCount :: Tree a -> Integer,使用 fold 和最多一个辅助函数,我想我需要在不同的情况下区分叶子和节点,但我很难做到这一点,这里是我现在的代码:

leafCount = fold sum (Node a left right)
            where 
            sum left right elem = leafCount left + leafCount right + 1

现在这段代码中有很多错误,我根本无法弄清楚。请给我基本的想法和可以改进我的代码。

您的直接问题是您在 =:

的错误一侧进行模式匹配
leafCount (Node a left right) = fold sum left right a
       where sum l r elem = leafCount left + leafCount right + 1

其实很简单,我用的时候忘了加上fold函数的base case!

看了折叠的东西,问了别人,我明白了!