-1

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.

Community
  • 1
  • 1
o1xhack
  • 87
  • 9
  • Given that this is a homework assignment, I'm not sure you should be seeking this much help from StackOverflow... Perhaps you could formulate a question about a specific error you are getting? – Alec Oct 11 '16 at 23:42
  • @Alec well, I've been told that not in scope a, left and right. – o1xhack Oct 11 '16 at 23:46
  • @o1xhack one way to stay clean (during haskell development) is to add type signatures to all of your (top-level) functions, and if something is not in scope - you might try to add it on the left hand side of your function definition. Another hint I want to give - `sum` is something already defined - you are shadowing the original definition, which is usually a bad idea. Turn on `-Wall` when compiling - this saves you a lot of hassle in the long run. – epsilonhalbe Oct 12 '16 at 00:03
  • @epsilonhalbe what do you mean turn on -Wall? I'm using sublime to build. Like I first said , I define Tree a wither leaf or node, this isn't enough? – o1xhack Oct 12 '16 at 00:10
  • `-Wall` is a `ghc-option` that shows all warnings, but nevermind; the problem you have I think is that you try to think too advanced, take a simple recursive function and define a case for `countLeaves Leaf = …` and one `countLeaves (Node x l r) = …` and you should be fine, don't worry yet about `folding`, `traversing` and whatnot - you'll learn it soon enough. – epsilonhalbe Oct 12 '16 at 00:13
  • Seems like there is a misunderstanding of the role and semantics of `fold` - since you are to use the `fold` function, perhaps you should review its semantics. – user2407038 Oct 12 '16 at 04:08

2 Answers2

1

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
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Maybe we should clarify that this does not fix the code, there are other issues the OP has to solve. – chi Oct 12 '16 at 08:08
0

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!

o1xhack
  • 87
  • 9