[Haskell-beginners] question about pattern guards

Graham Gill math.simplex at gmail.com
Sat Sep 21 17:42:43 CEST 2013


That works with Maybe, but not with lists.

If I want at least one of xs or ys to match a two element list then

f xs ys
   | [_,_] <- xs <|> ys = ...

won't behave as expected, since <|> is ++ for lists, so

f [1] [2]

will match the pattern. Undoubtedly there are other type- and 
example-specific ways to encode the alternative for lists and other 
examples. I think what the OP is asking though, is why pattern 
alternatives aren't allowed in pattern guards (or in patterns in 
function definitions, or in case statements). I'm guessing that the 
major problem is binding? Suppose the token "or" introduces pattern 
alternatives:

g xs ys
   | (_:_:xrest) <- xs) or ([y1] <- ys) = ...

The pattern matches if xs has at least two elements or if ys is a one 
element list. But after the match you don't know which names have been 
bound. I guess there are ways to deal with that problem, like requiring 
every pattern alternative to bind exactly the same set of names and 
types, but sounds like that would get pretty hairy. How do other 
languages that allow "or patterns" handle binding?

Graham

On 21/09/2013 9:34 AM, Daniel Trstenjak wrote:
>
> > What am I missing?
>
> You can combine booleans by '||', but 'Just n <- x' doesn't result to 
> a boolean.
>
> You can use '<|>' from 'Control.Applicative' to get the desired behavoir.
>
> f x y
>    | Just _ <- x <|> y = 1
>    | otherwise           = 2
>
> Greetings,
> Daniel
>
>
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20130921/15b8e925/attachment.htm>


More information about the Beginners mailing list