-
Notifications
You must be signed in to change notification settings - Fork 0
/
Logger.hs
61 lines (53 loc) · 1.6 KB
/
Logger.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
module Logger (
Logger
, Log
, runLogger
, record
) where
import Control.Monad
type Log = [String]
newtype Logger a = Logger { execLogger :: (a, Log) }
runLogger :: Logger a -> (a, Log)
runLogger = execLogger
record :: String -> Logger ()
record s = Logger ((), [s])
instance Monad Logger where
return a = Logger (a, [])
m >>= k = let (a, w) = execLogger m
n = k a
(b, x) = execLogger n
in Logger (b, w ++ x)
globToRegex :: String -> Logger String
globToRegex cs = do
ds <- globToRegex' cs
return ('^':ds)
globToRegex' :: String -> Logger String
globToRegex' "" = return "$"
globToRegex' ('?':cs) = do
record "any"
ds <- globToRegex' cs
return ('.':ds)
globToRegex' ('*':cs) = do
record "kleene star"
ds <- globToRegex' cs
return (".*" ++ ds)
globToRegex' ('[':'!':c:cs) = do
record "character class, negative"
ds <- charClass cs
return ("[^" ++ c : ds)
globToRegex' ('[':c:cs) = do
record "character class, postive"
ds <- charClass cs
return ('[':c:ds)
globToRegex' ('[':_) =
fail "unterminated character class"
globToRegex' (c:cs) = liftM2 (++) (escape c) (globToRegex' cs)
escape :: Char -> Logger String
escape c
| c `elem` regexChars = record "escape" >> return ['\\', c]
| otherwise = return [c]
where regexChars = "\\+()^$.{}]|"
charClass :: String -> Logger String
charClass ('[':_) = fail "unterminated character class"
charClass (']':cs) = (']':) `liftM` globToRegex' cs
charClass (c:cs) = (c:) `liftM` charClass cs