The underlying problem here is that this does not look like a guard: a guard is an expression with type Bool
, this determines if the guard "fires" or not. Here this is likely `otherwise:
pathTo :: Eq a => a -> Tree a -> Maybe Path
pathTo a End = Nothing
pathTo a (Node b l r)
| a == b = Just []
| otherwise = case (pathTo a l) of
Just p -> Just (L:p)
Nothing -> case (pathTo a r) of
Just p -> Just (R:p)
Nothing -> Nothing
This also revealed some extra mistakes: Just [L:p]
is a Maybe [[Step]]
, you likely wanted to use Just (L:p)
, the same applies for Just [R:p]
.
You furthermore do not need to use nested case
s, you can work with the Alternative
typeclass:
import Control.Applicative((<|>))
pathTo :: Eq a => a -> Tree a -> Maybe Path
pathTo a End = Nothing
pathTo a (Node b l r)
| a == b = Just []
| otherwise = ((L:) <$> pathTo a l) <|> ((R:) <$> pathTo a r)
Here x <|> y
will take x
if it is a Just …
, and y
otherwise. We use (L:) <$> …
to prepend the list wrapped in the Just
data constructor, or return Nothing
in case …
is Nothing
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…