在Haskell中,在处理守卫时where子句的范围是什么? [英] In Haskell, what is the scope of a where clause when dealing with guards?

查看:296
本文介绍了在Haskell中,在处理守卫时where子句的范围是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道他们不支持跨模式匹配(即,您需要为每个模式重写'where'子句),但是对于警卫人员的范围工作如何?

例如这是否工作?

  myFunction x1 x2 
| x1> x2 = addOne x1
| x1< x2 = addOne x2
|否则= x1
其中addOne =(1+)

或者应该是这个吗?

  myFunction x1 x2 
| x1> x2 = addOne x1
其中addOne =(1+)
| x1< x2 = addOne x2
其中addOne =(1+)
|否则= x1


解决方案

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


I know they do not hold across pattern matches (i.e. you need to rewrite the 'where' clause for each pattern), but how does the scoping work for guards?

e.g. Does this work?

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

Or should it be this?

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

解决方案

The first one is the correct one. I would suggest you to have a look at the let vs where page on the haskell wiki, it's a good reading (and it explains also how to deal with scoping). Just as a note, you should never repeat the same definitions... it's a sign that your code needs to be structured in another way.

这篇关于在Haskell中,在处理守卫时where子句的范围是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆