first-class-patterns-0.2.0: First class patterns and pattern matching, using type families

MaintainerReiner Pope <>




Common pattern combinators.


Basic patterns

var :: Pattern (a :*: Nil) aSource

"Variable patterns": always succeeds, and binds the value to a variable.

__ :: Pat0 aSource

"Wildcard patterns": always succeeds. (This is written as two underscores.)

(/\) :: Pat2 a a aSource

"And patterns". Succeeds only if both patterns succeed.

(/\) = mk2 (a -> (a,a))

(\/) :: Pattern as a -> Pattern as a -> Pattern as aSource

"Or patterns". If first pattern fails, then tries the second.

view :: (a -> b) -> Pat1 b aSource

"View patterns": do some computation, then pattern match on the result.

tryView :: (a -> Maybe b) -> Pat1 b aSource

"Partial view patterns". Synonym for mk1.

Non-binding patterns

is :: (a -> Bool) -> Pat0 aSource

"Predicate pattern". mk0 but with Bool instead of Maybe (). Succeeds if function yields True, fails otherwise.

Can be used with (/\) for some uses similar to pattern guards:

match a $ 
      left (var /\ is even) ->> id
  ||| left __               ->> const 0
  ||| right __              ->> const 1

cst :: Eq a => a -> Pat0 aSource

"Constant patterns": tests for equality to the given constant. cst x = is (==x)

Anonymous matching

elim :: Clause a r -> a -> rSource

elim = flip match

Useful for anonymous matching (or for building eliminators, like either). For example:

either withLeft withRight = elim $
              left  var ->> withLeft
          <|> right var ->> withRight

Monadic matching

mmatch :: Monad m => m a -> Clause a (m b) -> m bSource

mmatch m p = m >>= elim p

Useful for applicative-looking monadic pattern matching, as in

ex7 :: IO ()
ex7 = mmatch getLine $
       cst "" ->> return ()
   <|> var    ->> putStrLn . ("You said " ++)

Smart constructors for patterns

These build patterns from a selector function.

mk0 :: (a -> Maybe ()) -> Pat0 aSource

mk1 :: (a -> Maybe b) -> Pat1 b aSource

mk2 :: (a -> Maybe (b, c)) -> Pat2 b c aSource

mk3 :: (a -> Maybe (b, c, d)) -> Pat3 b c d aSource

mk4 :: (a -> Maybe (b, c, d, e)) -> Pat4 b c d e aSource

mk5 :: (a -> Maybe (b, c, d, e, f)) -> Pat5 b c d e f aSource

Tuple patterns

tup0 :: Pat0 ()Source

"0-tuple pattern". A strict match on the ().

tup1 :: Pat1 a aSource

"1-tuple pattern". Rather useless.

tup2 :: Pat2 a b (a, b)Source

"2-tuple pattern"

tup3 :: Pat3 a b c (a, b, c)Source

"3-tuple pattern"

tup4 :: Pat4 a b c d (a, b, c, d)Source

"4-tuple pattern"

tup5 :: Pat5 a b c d e (a, b, c, d, e)Source

"5-tuple pattern"

Either patterns

left :: Pat1 a (Either a b)Source

Matches the Left of an Either.

right :: Pat1 b (Either a b)Source

Matches the Right of an Either.

List patterns

cons :: Pat2 a [a] [a]Source