Reputation: 3
I am new in Haskell Programming and I have tried to code and manipulate a Haskell n-ary tree defined as
data Tree = Empty | Node Integer [Tree]
I want to write a sum
function for this tree structure, but I did not figure it out. The function I coded is here:
sumall Empty = 0
sumall (Node a (x:xy) ) = a + (sumall x)
Input: (Node 5 [Node 2 [Node 1 [Empty]],Node 8 [Node 7 [Node 6 [Empty]],Node 12 [Node 10 [Node 9 [Empty]],Node 13 [Node 15 [Empty]]]]] )
The result = 8.
How to develop this function to sum all the elements in this tree? Thanks in advance.
Upvotes: 0
Views: 776
Reputation: 81
import qualified Data.Foldable as F
instance F.Foldable Tree where
foldMap f Empty = mempty
foldMap f (Node a ts) = mconcat $ f a : map (F.foldMap f) ts
sumall = F.sum
without Foldable you would do something like
sumall Empty = 0
sumall (Node a ts) = a + foldr (+) 0 (map sumall ts)
Upvotes: 3