在Haskell中,在处理守卫时where子句的范围是什么?

时间:2012-03-15 14:03:59

标签: haskell scope pattern-matching where-clause

我知道他们没有跨越模式匹配(即你需要为每个模式重写'where'子句),但是范围如何对守卫起作用?

e.g。这有用吗?

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

2 个答案:

答案 0 :(得分:16)

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

答案 1 :(得分:5)

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