[Haskell-cafe] Prolog-style patterns

Tillmann Rendel rendel at informatik.uni-marburg.de
Mon Apr 8 14:06:12 CEST 2013


Hi,

Jan Stolarek wrote:
> If Haskell allowed to write pattern matching similar to Prolog then we could write this function
> like this:
>
> member :: Eq a => a -> [a] -> Bool
> member _ []     = False
> member x (x:_)  = True
> member x (_:xs) = member x xs
>
> The meaning of pattern in the second equation is "match this equation if the first argument equals
> to head of the list".

You can achieve something similar with the ViewPatterns language 
extension. See 
http://www.haskell.org/ghc/docs/latest/html/users_guide/syntax-extns.html#view-patterns 
and http://hackage.haskell.org/trac/ghc/wiki/ViewPatterns.

member _ [] = False
member x (((x ==) -> True) : _) = True
member x (_ : xs) = member x xs

or

member _ [] = False
member x ((compare x -> EQ) : _) = True
member x (_ : xs) = member x xs

   Tillmann



More information about the Haskell-Cafe mailing list