我希望能夠指定一個元素,樹和函式應該給我一個方向串列,如果該元素不包含它不應該回傳錯誤,而是由 Maybe 制作的“Nothing”。
data BTree a = Nil | Node a ( BTree a) ( BTree a) deriving Show
data Direction = L | R deriving (Show , Eq)
getPath :: (Ord a) => a -> BTree a -> Maybe [Direction]
getPath y (Node x lt rt)
| (Node x lt rt) == Nil = Nothing
| y == x = Just []
| y < x = Just (L:(getPath y lt))
| otherwise = Just (R:(getPath y rt))
但是使用這段代碼我得到一個錯誤:
* Couldn't match expected type: [Direction]
with actual type: Maybe [Direction]
* In the second argument of `(:)', namely `(getPath y lt)'
In the first argument of `Just', namely `(L : (getPath y lt))'
In the expression: Just (L : (getPath y lt))
|
57 | | y < x = Just (L:(getPath y lt))
* Couldn't match expected type: [Direction]
with actual type: Maybe [Direction]
* In the second argument of `(:)', namely `(getPath y rt)'
In the first argument of `Just', namely `(R : (getPath y rt))'
In the expression: Just (R : (getPath y rt))
|
58 | | otherwise = Just (R:(getPath y rt))
如果有人可以幫助我,那就太好了。
uj5u.com熱心網友回復:
Just (L : getPath y lt)不起作用的原因是因為getPath y lt是 a Maybe [Direction],而不是 a [Direction],因此它不是串列,因此您不能在此前面加上Lor R。
您可以使用 對fmap :: Functor f => (a -> b) -> f a -> f b包裝在Just資料建構式中的專案執行映射,fmap f Nothing并將回傳Nothing.
因此,您可以將其實作為:
getPath :: Ord a => a -> BTree a -> Maybe [Direction]
getPath Nil = Nothing
getPath y (Node x lt rt)
| y == x = Just []
| y < x = fmap (L:) (getPath y lt)
| otherwise = fmap (R:) (getPath y rt)
條件(Node x lt rt) == Nil永遠不能是True:您應該在模式匹配上Nil,在這種情況下回傳Nothing。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/411553.html
標籤:
上一篇:定義一個可以與任何可折疊型別一起使用的filterF函式
下一篇:關于可折疊Maybe實體的問題
