In Haskell, what is the scope of a where clause when dealing with guards?

二次信任 提交于 2019-12-08 14:43:23

问题


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

回答1:


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.




回答2:


The scope of the where clause is the whole equation, so your first example works.



来源:https://stackoverflow.com/questions/9721354/in-haskell-what-is-the-scope-of-a-where-clause-when-dealing-with-guards

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!