haskell - 范围 : where for multiple polymorphic patterns

标签 haskell

已接受的答案 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 确实应该被视为两个同名变量。

如果您希望 xwhere 子句中可见,则必须将其绑定(bind)在 = 符号的左侧。实现此目的的一种方法是将 xPolyTree 类型中分解出来。

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/

相关文章:

haskell - 具有可能多态参数的函数的类型签名

haskell - 无压缩单子(monad)变压器

arrays - Haskell Data.Vector.Storable.unsafeFromForeignPtr 与 C 结构指针/数组字段

haskell - 在 Cloud9 中运行 Yesod

haskell - 声明适用于具有特定字段的 Vinyl 记录的约束

python - 从 Haskell 调用 Sage

haskell - `wreq` Get/Post 带异常处理

haskell - 具有 `put` 函数的状态 Monad

haskell - 多态种类的用途是什么?

java - Haskell 的类型系统是否遵循 Liskov 替换原则?