简体   繁体   中英

How to sum the elements of a n-ary Haskell Tree?

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.

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)

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