parsing - 在guards haskell中使用case表达式时解析错误

标签 parsing haskell functional-programming syntax-error case

我是 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/

相关文章:

parsing - 保留语法关联性/优先级的手写自上而下的解析器?

haskell - 多参数类没有实例错误

haskell - 处理纯代码抛出的 `try`异常

r - 循环遍历 R 中有序集的功能方法

java - SAX 解析器由于 <br/> 标记而忽略文本

java - Jsoup 仅选择带有其他元素的 div 中的文本

c++ - 按分隔符拆分字符串 strtok 奇怪的行为

haskell - 我可以让 Stack 使用我打过补丁的 Cabal 库吗?

functional-programming - 比较 Racket 中的日期

scala - 在 Scala 中转换仿函数 (F[A] => G[A])(cats 或 scalaz)