Debian Codegraph @

Text/RE/ZeInternals/Types/Matches.lhs

raw
1 \begin{code}
2 {-# LANGUAGE RecordWildCards #-}
3 {-# LANGUAGE FlexibleContexts #-}
4 {-# LANGUAGE FlexibleInstances #-}
5 {-# LANGUAGE UndecidableInstances #-}
6 {-# LANGUAGE MultiParamTypeClasses #-}
7 {-# LANGUAGE DeriveDataTypeable #-}
8 {-# LANGUAGE MonoLocalBinds #-}
9 \end{code}
10
11 \begin{code}
12 module Text.RE.ZeInternals.Types.Matches
13 ( Matches(..)
14 , anyMatches
15 , countMatches
16 , matches
17 , mainCaptures
18 ) where
19 \end{code}
20
21 \begin{code}
22 import Data.Typeable
23 import Text.RE.ZeInternals.Types.Capture
24 import Text.RE.ZeInternals.Types.CaptureID
25 import Text.RE.ZeInternals.Types.Match
26 import Text.Regex.Base
27 \end{code}
28
29
30 \begin{code}
31 -- | the result of matching a RE against a text (with @*=~@), retaining
32 -- the text that was matched against
33 data Matches a =
34 Matches
35 { matchesSource :: !a -- ^ the source text being matched
36 , allMatches :: ![Match a] -- ^ all 'Match' instances found, left to right
37 }
38 deriving (Show,Eq,Typeable)
39 \end{code}
40
41 \begin{code}
42 instance Functor Matches where
43 fmap f Matches{..} =
44 Matches
45 { matchesSource = f matchesSource
46 , allMatches = map (fmap f) allMatches
47 }
48 \end{code}
49
50 \begin{code}
51 -- | tests whether the RE matched the source text at all
52 anyMatches :: Matches a -> Bool
53 anyMatches = not . null . allMatches
54
55 -- | count the matches
56 countMatches :: Matches a -> Int
57 countMatches = length . allMatches
58
59 -- | list the texts that Matched
60 matches :: Matches a -> [a]
61 matches = map capturedText . mainCaptures
62
63 -- | extract the main capture from each match
64 mainCaptures :: Matches a -> [Capture a]
65 mainCaptures ac = [ capture c0 cs | cs<-allMatches ac ]
66 where
67 c0 = IsCaptureOrdinal $ CaptureOrdinal 0
68 \end{code}
69
70 \begin{code}
71 -- | this instance hooks 'Matches' into regex-base: regex consumers need
72 -- not worry about any of this
73 instance
74 ( RegexContext regex source [MatchText source]
75 , RegexLike regex source
76 , RegexFix regex source
77 ) =>
78 RegexContext regex source (Matches source) where
79 match r s = Matches s $ map (convertMatchText r s) $ match r s
80 matchM r s = do
81 y <- matchM r s
82 return $ Matches s $ map (convertMatchText r s) y
83 \end{code}