[Haskell-beginners] question about pattern guards

Stuart Gale bishboria at gmail.com
Sat Sep 21 13:35:57 CEST 2013


I believe the structure you are looking for is called an "Or Pattern", which isn't available in Haskell. Or Patterns are available in other FP languages.

One way you could reduce the duplication from the right hand side, for more complicated examples, would be to create a separate function and call it instead.

Cheers,
Stuart

On 21 Sep 2013, at 12:08, TP <paratribulations at free.fr> wrote:

> 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
> 
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners



More information about the Beginners mailing list