【问题标题】:In Haskell, what is the scope of a where clause when dealing with guards?在 Haskell 中,处理守卫时 where 子句的范围是什么?
【发布时间】:2012-04-01 01:21:53
【问题描述】:

我知道它们不能跨越模式匹配(即您需要为每个模式重写 'where' 子句),但范围界定如何对守卫起作用?

例如这行得通吗?

myFunction x1 x2
    | x1 > x2 = addOne x1
    | x1 < x2 = addOne x2
    | otherwise = x1
        where addOne = (1+)

还是应该这样?

myFunction x1 x2
    | x1 > x2 = addOne x1
        where addOne = (1+)
    | x1 < x2 = addOne x2
        where addOne = (1+)
    | otherwise = x1

【问题讨论】:

    标签: haskell scope pattern-matching where-clause


    【解决方案1】:

    第一个是正确的。我建议您查看 haskell wiki 上的 let vs where 页面,这是一本很好的阅读材料(它还解释了如何处理范围界定)。 请注意,您永远不应该重复相同的定义......这表明您的代码需要以另一种方式构建。

    【讨论】:

      【解决方案2】:

      where 子句的范围是整个等式,因此您的第一个示例有效。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-26
        • 1970-01-01
        • 2012-10-30
        • 2011-09-27
        • 2017-11-27
        • 1970-01-01
        相关资源
        最近更新 更多