我想使用我定義的foldTree函數和按順序遍歷實現扁平化樹。在扁平化後應該返回一個列表。使用按順序遍歷扁平化haskell中的樹
data Tree t = Leaf t
| Tree (Tree t) t (Tree t)
foldTree :: (t1 -> t -> t1 -> t1) -> (t -> t1) -> Tree t -> t1
foldTree treeFn leafFn tree =
case tree of
Leaf v -> leafFn v
Tree leftTree q rightTree -> treeFn (foldTree treeFn leafFn leftTree) q (foldTree treeFn leafFn rightTree)
Input : foldTree (\t1 t t2->t1 + 5*t + t2) (\x->x+9) (Leaf 5)
Expected Output : 14
Input : foldTree (\t1 t t2->t1 + 3*t + t2) (\x->x+5) (Tree (Leaf 3) 2 (Leaf 4))
Expected Output : 23
我嘗試下面的代碼,但它使用recursion.I想從flattenTree調用foldTree實現樹的扁平化,而不是製造遞歸調用flatTree的。(使用flattenTree foldTree功能)。可任何人的幫助我如何整合它。
flatTree :: Tree a -> [a]
flatTree tree =
case tree of
Leaf v -> [v]
Tree p v r -> (flatTree p) ++ [v] ++ (flatTree r)
Input: flatTree (Tree (Leaf 5) 3 (Tree (Leaf 3) 2 (Leaf 4)))
Expected output : [5,3,3,2,4]