简体   繁体   English

Haskell-为树类型创建折叠功能

[英]Haskell - Create a fold function for tree type

I have this simple data Tree : 我有这个简单的数据树:

data Tree = Leaf Int | Node [Tree]

And I have to devellop a fold function for this type : 我必须为此类型设计一个折叠函数:

foldTree :: (Int -> a) -> ([a] -> a) -> Tree -> a

for example : 例如 :

foldTree (+1) sum (Node[ (Leaf 2), (Leaf 3)]) 

will return (2+1)+(3+1) = 7 For leafs, I have : 将返回(2 + 1)+(3 + 1)= 7对于叶子,我有:

foldTree f g (Leaf n)  = (f n)

But I have no ideas for develop the nodes's case. 但是我没有开发节点案例的想法。

I'm french, also sorry for the mistakes. 我是法国人,也为自己的错误感到抱歉。

It sometimes helps to look at what is available in scope and their types. 有时有助于查看范围及其类型中可用的内容。 Here's a solution: 这是一个解决方案:

foldTree f g (Leaf n)  = (f n)
foldTree f g (Node subtrees)  = 
  let as = map (foldTree f g) subtrees -- as :: [a]
  in g as

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM