已接受的答案 this SO post展示如何使用 case ... of
在多个模式匹配中利用 where
定义。现在就我而言,这似乎不起作用(ghc 提示:变量不在范围内:x
)。
data PolyTree a = PolyBranch a (PolyTree a) (PolyTree a) | PolyLeaf a
paths' :: PolyTree a -> [a] -> PolyTree [a]
paths' pt buf = case pt of
(PolyLeaf x) -> PolyLeaf buf'
(PolyBranch x pt1 pt2) -> PolyBranch buf' (paths' pt1 buf') (paths' pt2 buf')
where buf' = buf ++ [x]
我可以用其他方法吗?
最佳答案
在您的示例中,buf'
是根据 x
定义的,它由内部 case
表达式绑定(bind),而 其中
实际上是右侧表达式的“外部”。
paths' pt buf =
(case ... of ... -> ...(1) ; ... -> ...(2) )
where ...(3)
x
仅在 (1)
和 (2)
中可见,但在 (3)
中不可见。 (1)
和 (2)
中出现 x
确实应该被视为两个同名变量。
如果您希望 x
在 where
子句中可见,则必须将其绑定(bind)在 =
符号的左侧。实现此目的的一种方法是将 x
从 PolyTree
类型中分解出来。
data PolyTree a = PolyTree a (PolyBranch a)
data PolyBranch a = PolyBranch (PolyTree a) (PolyTree a) | PolyLeaf
paths' (PolyTree x pt) buf = ...
where buf' = buf ++ [x]
关于haskell - 范围 : where for multiple polymorphic patterns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43559234/