简体   繁体   中英

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.

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 = 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!

After I reading the fold stuff and ask other person, I figure this out!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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