我正在嘗試使用 foldTree 定義一個 minTree 函式:
foldTree :: (b -> a -> b -> b) -> b -> Tree a -> b
foldTree f e Leaf = e
foldTree f e (Node left x right) = f (foldTree f e left) x (foldTree f e right)
這是我到目前為止所擁有的。
minTree :: (Ord a) => Tree a -> Maybe a
minTree f e Leaf = e
minTree tree = foldTree f e tree
where
f x nothing = Just x
f x (Just y) = Just (min x y)
e = Nothing
但是這段代碼不起作用,并給出了一些我不明白如何修復的錯誤。有人可以幫我找出問題所在以及如何解決。
uj5u.com熱心網友回復:
在你的例子中b ~ Maybe a。因此,這意味著 的第一個和第三個引數f是Maybe as。因此,您需要檢查兩者。第二項是一個a。f因此,您應該確定兩個Maybe as 和 an的最小值,a例如:
minTree :: Ord a => Tree a -> Maybe a
minTree tree = foldTree f Nothing tree
where f Nothing y Nothing = Just y
f Nothing y (Just z) = …
f (Just x) y Nothing = …
f (Just x) y (Just z) = …
我將實作這些…部分作為練習。由于a是Ord型別類的成員,您可以使用min :: Ord a => a -> a -> a.
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/350107.html
