简体   繁体   English

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

[英]Haskell: leafCount function take Tree output Int using fold fun

I define Tree type as:我将树类型定义为:

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

Here are a fold function : How to write a function of type a-> b -> b -> b for folding a tree , basically same as what I using.这是一个折叠函数: 如何编写 a-> b -> b -> b 类型的函数来折叠树,与我使用的基本相同。

Now I want to write a function leafCount :: Tree a -> Integer , using fold and at most one helper function, I think I need to distinct leaf and node in different situation but I'm struggle with doing this, here is my code for now:现在我想写一个函数leafCount :: Tree a -> Integer ,使用 fold 和最多一个辅助函数,我想我需要在不同的情况下区分叶子和节点,但我很难做到这一点,这是我的代码目前:

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

There are lot of errors in this code now that I cannot figure out at all.这段代码中有很多错误,我根本无法弄清楚。 Please give me the basic idea and the code that can improve mine.请给我基本的想法和可以改进我的代码。

Your immediate problem is that you are doing the pattern matching on the wrong side of the = :您当前的问题是您在=的错误一侧进行模式匹配:

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

It's really easy actually, I forget to add the base case of the fold function when using it!其实真的很简单,我用的时候忘记加fold函数的base case了!

After I reading the fold stuff and ask other person, I figure this out!在我阅读折叠内容并询问其他人后,我明白了这一点!

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

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