【发布时间】:2014-02-07 20:25:15
【问题描述】:
考虑以下类型:
data LTree a = Leaf a | Fork (LTree a) (LTree a)
现在考虑以下列出树的叶子及其深度的函数
tolistdepth :: LTree a -> [(a,Int)]
tolistdepth (Leaf x) = [(x,0)]
tolistdepth (Fork e d) = map (\(x,n) -> (x,n+1)) (tolistdepth e ++ tolistdepth d)
我需要帮助定义以下函数
build :: [(a, Int)] -> LTree a
计算第一个函数的逆函数,以便
build (tolistdepth a) = a
我什至不知道从哪里开始:)
我已经设法做到了以下几点:
build :: [(a, Int)] -> LTree a
build xs = let ys= map (\(x, n) -> (Leaf x, n)) xs
in SOMETHING iterateUntil SOMETHING (buildAssist ys)
buildAssist :: [(LTree a, Int)] -> [(LTree a, Int)]
buildAssist [] = []
buildAssist [x] = [x]
buildAssist (x@(t1, n1):y@(t2, n2):xs) = if n1 == n2 then ((Fork t1 t2), n1 - 1):buildAssist xs
else x:(buildAssist (y:xs))
这样,我想我已经处理了何时分叉。 现在,如何在我的原始函数中使用 buildAssist(如果 buildAssist 当然有用的话)?
我相信我已经弄明白了。
如果可行,请告诉我:
build :: [(a,Int)] -> LTree a
build l = fst (buildaccum 0 l)
buildaccum :: Int -> [(a,Int)] -> (LTree a, [(a,Int)])
buildaccum n l@((a,b):t) |n==b = (Leaf a,t)
|n<b = (Fork e d, l2)
where (e,l1) = buildaccum (n+1) l
(d,l2) = buildaccum (n+2) l1
【问题讨论】:
-
你对构建的论点有什么假设?并非所有可能的输入都可以生成树。
-
@ChrisTaylor 假设输入可以做成一棵树。谢谢指出
-
我认为你可以使用你的
buildAssist,如果你继续调用它直到你得到一个元素。 -
@user5402 你能详细说明我该怎么做吗?
-
我更新了我的答案。一旦你的方法奏效,我会发布我想到的解决方案。
标签: list haskell tree higher-order-functions