danieltahara
danieltahara

Reputation: 4993

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

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

Upvotes: 18

Views: 4275

Answers (2)

Riccardo T.
Riccardo T.

Reputation: 8937

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.

Upvotes: 16

dave4420
dave4420

Reputation: 47042

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

Upvotes: 6

Related Questions