[英]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 我是Haskell编程的新手,我尝试编码和操作定义为的Haskell n元树
data Tree = Empty | Node Integer [Tree]
I want to write a sum
function for this tree structure, but I did not figure it out. 我想为此树形结构编写一个
sum
函数,但我没有弄清楚。 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]]]]] )
输入:(
(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. 结果= 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.