Fold into a binary tree in Haskell

Asked

Viewed 114 times

0

Hello, I am trying to define the foldTree function that receives a function and a binary polymorphic tree as parameters and returns the resulting value of accumulating the application of this function by all nodes of the tree. Then sum all the tree nodes using this foldTree function and using only recursion

I’m defining my tree as:

data Tree a = Nulo 
            | No a (Tree a) (Tree a)
            deriving (Eq, Ord, Read, Show)

Filling in the tree

tree1 :: Tree Int
tree1 = No 1 Nulo (No 2 Nulo(No 3 Nulo Nulo))

FoldTree function

foldTree :: (b -> b -> b) -> Tree a -> b
foldTree f Nulo = 0
foldTree f (No a e d) = f (foldTree f e)(foldTree f d) 

And finally the functions somaTree and somaTree with Folding

somaTree :: Tree a -> Int
somaTree Nulo = 0
somaTree (No a e d) = 

somaTreeFold :: Tree a -> Int
  • Try to show what you’ve already tried. What have you tried? Managed to compile? If so, was the result expected? If not, what kind of error did you get?

  • The doubt was on the application of foldTree function, it was not compiling, it had pattern matching error. The solution I found was to turn the tree into a list and fold the list, when applying fold directly on the tree I could not.

  • 1

    You should show how you implemented it so someone can tell you where the bug is or try to help you improve it.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.