Parsing 在guards haskell中使用大小写表达式时出现分析错误
我是Haskell的新手,语法有问题。我要做的是给定数据和此数据类型的树,找到树中相应节点的路径。我相信我的函数逻辑是正确的,但我不确定如何使它有效。我尝试过将选项卡更改为空格Parsing 在guards haskell中使用大小写表达式时出现分析错误,parsing,haskell,functional-programming,syntax-error,case,Parsing,Haskell,Functional Programming,Syntax Error,Case,我是Haskell的新手,语法有问题。我要做的是给定数据和此数据类型的树,找到树中相应节点的路径。我相信我的函数逻辑是正确的,但我不确定如何使它有效。我尝试过将选项卡更改为空格 -- | Binary trees with nodes labeled by values of an arbitrary type. data Tree a = Node a (Tree a) (Tree a) | End deriving (Eq,Show) -- | One step in a
-- | Binary trees with nodes labeled by values of an arbitrary type.
data Tree a
= Node a (Tree a) (Tree a)
| End
deriving (Eq,Show)
-- | One step in a path, indicating whether to follow the left subtree (L)
-- or the right subtree (R).
data Step = L | R
deriving (Eq,Show)
-- | A path is a sequence of steps. Each node in a binary tree can be
-- identified by a path, indicating how to move down the tree starting
-- from the root.
type Path = [Step]
pathTo :: Eq a => a -> Tree a -> Maybe Path
pathTo a End = Nothing
pathTo a (Node b l r)
| a == b = Just []
| case (pathTo a l) of
Just p -> Just [L:p]
Nothing -> case (pathTo a r) of
Just p -> Just [R:p]
Nothing -> Nothing
这就是错误:
parse error (possibly incorrect indentation or mismatched brackets)
这里潜在的问题是,它看起来不像一个保护:保护是一个类型为
Bool
的表达式,这决定了保护是否“启动”。这里很可能是`否则:
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
这里
xy
如果是x
,则取x
,否则取y
。我们使用(L:)…
来预先包装在Just
数据构造函数中的列表,或者返回Nothing
,以防是Nothing
这看起来不像一个守卫,否则需要否则=…
这看起来不像是一个解析错误,您的类型错误。您的编辑使答案与问题无关。如果您有后续问题,请发布新问题。
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)