我是 Haskell 的新手,我遇到了语法问题。我想要做的是给定数据和这种数据类型的树,找到树中相应节点的路径。我相信我对该函数的逻辑是正确的,但我不确定如何使它有效的 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 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
这也暴露了一些额外的错误:Just [L:p]
是 Maybe [[Step]]
,您可能想使用 Just (L:p)
,同样适用于 Just [R:p]
.此外,您不需要使用嵌套
case
s,您可以使用 Alternative
类型类: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)
这里x <|> y
将采取x
如果是 Just …
, 和 y
除此以外。我们使用 (L:) <$> …
将列表放在 Just
中数据构造函数,或返回 Nothing
万一…
是 Nothing
.
关于parsing - 在guards haskell中使用case表达式时解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65800969/