还有其他方法可以通过 BTree 在我的路径搜索功能上使用 Maybe 吗? (Haskell)

Is there a other way to use Maybe on my path search function through the BTree? (Haskell)

我希望能够指定一个元素,树和函数应该给我一个方向列表,如果不包含该元素,它不应该 return 一个错误,而是一个“无”由 Maybe 制作。

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))

如果有人能帮助我就太好了。

Just (L : getPath y lt) 不起作用的原因是因为 getPath y ltMaybe [Direction],而不是 [Direction],因此它不是列表,因此您不能在前面加上 LR.

您可以使用 fmap :: Functor f => (a -> b) -> f a -> f b 对包裹在 Just 数据构造函数中的项目执行映射,并且 fmap f Nothing 将 return Nothing .

因此您可以将其实现为:

getPath :: Ord a => a -> BTree a -> Maybe [Direction]
getPath Nil = Nothing
getPath y (Node x lt rt)
    | y == x = Just []
    | y < x = <strong>fmap (L:)</strong> (getPath y lt)
    | otherwise = <strong>fmap (R:)</strong> (getPath y rt)

条件 (Node x lt rt) == Nil 永远不能是 True:你应该在 Nil 上进行模式匹配,在这种情况下 return Nothing.