【问题标题】:Haskell - Create a fold function for tree typeHaskell - 为树类型创建折叠函数
【发布时间】:2017-12-13 20:10:03
【问题描述】:

我有这个简单的数据树:

data Tree = Leaf Int | Node [Tree]

我必须为这种类型开发一个折叠功能:

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

例如:

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

将返回 (2+1)+(3+1) = 7 对于叶子,我有:

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

但我对开发节点的案例没有任何想法。

我是法国人,也为错误感到抱歉。

【问题讨论】:

  • 提示:如何从Trees 列表中获取as 列表?

标签: haskell tree fold


【解决方案1】:

查看范围内可用的内容及其类型有时会有所帮助。这是一个解决方案:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多