0
我做練習用二叉樹:錯誤類型
data BinaryTree a =
Leaf
| Node (BinaryTree a) a (BinaryTree a)
deriving (Show)
我實現了樹摺疊功能:
foldTree :: (a -> b -> b -> b) -> b -> BinaryTree a -> b
foldTree _ start Leaf = start
foldTree f start (Node left x right) = f x (foldTree f start left) (foldTree f start right)
現在我試圖重寫我的老地圖功能使用摺疊:
mapTree' :: (a -> b) -> BinaryTree a -> BinaryTree b
mapTree' f bt = foldTree (\l x r -> Node l (f x) r) Leaf bt
但是,它告訴我,x
在上述lambda類型爲二叉樹的
x :: BinaryTree b (bound at app/Main.hs:85:30)
我很困惑,因爲如果我在ghci
做:t Node
我得到:
Node :: BinaryTree a -> a -> BinaryTree a -> BinaryTree a
所以,在我的腦海x
應該a
型的,因爲它是在的中間位置Node
構造函數。
我哪裏錯了?
哦,我明白了!所以我在foldTree中的參數排序不符合我對Node的定義。 – m0meni