[Haskell-beginners] question about pattern guards

TP paratribulations at free.fr
Sat Sep 21 13:08:56 CEST 2013


Daniel Trstenjak wrote:

>> Why is it not possible to combine them with a logical OR, instead of the
>> comma that stands for a logical AND?
> 
> The '|' already acts as the "OR", why should you need another one?

Thanks for your answer.
Consider the following example:

------------------
type Foo = Maybe Int

f :: Foo -> Foo -> Int
f x y
  | Just n <- x = 1
  | Just n <- y = 1
  | otherwise = 2

main = do

print $ f (Just 3) Nothing
print $ f Nothing (Just 3)
print $ f (Just 3) (Just 3)
print $ f Nothing Nothing
------------------

It works correctly, but I am compelled to duplicate `1` even if I know that 
the result of `f x y` will be `1` if either `x` or `y` is `Just n`. Here the 
duplication is limited in terms of number of characters, but this may not 
always be so.
So I would like to do:

------------------
type Foo = Maybe Int

f :: Foo -> Foo -> Int
f x y
  | (Just n <- x) || (Just n <- y) = 1
  | otherwise = 2

main = do

print $ f (Just 3) Nothing
print $ f Nothing (Just 3)
print $ f (Just 3) (Just 3)
print $ f Nothing Nothing
------------------

But the `||` yields a parse error, `||` is not supported in pattern guards.
Whereas it is supported in classical guards:

------------------
f :: Int -> Int
f n | n == 1 = 1
    | n < 1 || n > 4 = 2
    | otherwise = 3

main = do

print $ f 1
print $ f 5
print $ f (-1)
print $ f 2
------------------

What am I missing?

Thanks in advance,

TP




More information about the Beginners mailing list