Finding max & sum of a tree in Haskell with map
2016-06-24 03:15
369 查看
Resume
I found an interesting algorithm to find the max and sum of a tree in Haskell using map. This algorithm is pretty short and useful for me.Type definition
data Tree = Leaf Int | Node [Tree]
In the definition above, we defined a tree. In the tree, we will have either a
Leaf Intor a
Node [Tree].
Attention: this is not a binary tree. It can have many sub-nodes within a node.
Sum
sum' :: Tree -> Int sum' (Leaf l) = l sum' (Node node) = sum (map sum' node)
We use a
mapto calculate every value of a
Leafin the tree, then construct a list with these values. Finally, we can figure out the sum of the tree.
Max
max' :: Tree -> Int max' (Leaf l) = l max' (Node node) = maximum (map max' node)
Like
sumabove, we can reuse it without major modification. Just replace
sumwith
maximum. Then this function will figure out the maximum value of this tree recursively.
Test
let tree = Node [Node [Leaf 4, Leaf 5], Leaf 6] *Main> let tree = Node [Node [Leaf 4, Leaf 5], Leaf 6] *Main> sum' tree 15 *Main> max' tree 6
相关文章推荐
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- C#递归算法之分而治之策略
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- C#算法之大牛生小牛的问题高效解决方法
- C#算法函数:获取一个字符串中的最大长度的数字
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- 经典排序算法之冒泡排序(Bubble sort)代码
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法