trufflewaffle
trufflewaffle

Reputation: 179

How to sum tree elements using folds?

I'm trying to learn the 'folds' (only 'foldr' and 'foldl') functionality of Haskell through doing some sample coding. I have defined a Tree (not binary) like so:

data NTree a = Nil | Tree a [NTree a] deriving Show

I want to sum all the elements of the tree using a function. I have outlined the type signature and the base case of the function, but I'm not sure how to implement the logic itself using folds. This is what I have so far:

sumElements :: NTree Int -> Int
sumElements Nil = 0
sumElements tree = foldr (???) 0 tree

I really can't think of how to get started. Any help filling in the folds function would be appreciated.

Upvotes: 0

Views: 412

Answers (2)

JulienKerlero
JulienKerlero

Reputation: 11

In order to apply foldr to your tree, you should define an instance of Foldable for your Tree. In short, you have to supply an implementation the 2 functions required for a data type to be "foldable" : foldMap and foldr.

You can learn more in this tutorial.

(Im also a begginer, I hope this will help you and others)

Upvotes: 1

Louis Wasserman
Louis Wasserman

Reputation: 198103

You pretty much have it.

sumElements tree = foldr (+) 0 tree

Upvotes: 2

Related Questions