19

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

2 Answers 2

17

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.

0
6

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.