Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 648
danieltahara Avatar asked Mar 15 '12 14:03

danieltahara


People also ask

What are guards in Haskell?

Haskell guards are used to test the properties of an expression; it might look like an if-else statement from a beginner's view, but they function very differently. Haskell guards can be simpler and easier to read than pattern matching .

Can you pattern match in guards Haskell?

The PatternGuards extension, now officially incorporated into the Haskell 2010 language, expands guards to allow arbitrary pattern matching and condition chaining. The existing syntax for guards then becomes a special case of the new, much more general form. You start a guard in the same way as always, with a | .

What is otherwise in Haskell?

In the prelude, it defines otherwise = True . Using it in a pattern match just shadows that definition, introducing a new, more local variable which also happens to be called otherwise .


2 Answers

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.

like image 111
Riccardo T. Avatar answered Sep 29 '22 21:09

Riccardo T.


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

like image 33
dave4420 Avatar answered Sep 29 '22 21:09

dave4420