-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMP.hs
More file actions
75 lines (59 loc) · 1.98 KB
/
MP.hs
File metadata and controls
75 lines (59 loc) · 1.98 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
module MP where
import System.Environment
type FileContents = String
type Keyword = String
type KeywordValue = String
type KeywordDefs = [(Keyword, KeywordValue)]
separators :: String
separators
= " \n\t.,:;!\"\'()<>/\\"
-----------------------------------------------------
lookUp :: String -> [(String, a)] -> [a]
lookUp x table = [ value | (key, value) <- table, key == x]
splitText :: [Char] -> String -> (String, [String])
splitText seps "" = ("", [""])
splitText seps (x : xs)
| x `elem` seps = (x : seps', "" : text)
| otherwise = (seps', (x : y) : ys)
where
(seps', text@(y : ys)) = splitText seps xs
combine :: String -> [String] -> [String]
combine "" wordList = wordList
combine (sep : seps) (word : words)
= word : ([sep] : combine seps words)
combine _ _ = [""]
getKeywordDefs :: [String] -> KeywordDefs
getKeywordDefs [] = []
getKeywordDefs (def : defs) = (y, def') : getKeywordDefs defs
where
(x : xs, y : ys) = splitText " " def
def' = concat (combine xs ys)
expand :: FileContents -> FileContents -> FileContents
expand text info
= concat [ replaceWord word defs | word <- lstText]
where
(seps, preText) = (splitText separators text)
lstText = combine seps preText
(_, keyDefs) = splitText "\n" info
defs = getKeywordDefs keyDefs
-- You may wish to uncomment and implement this helper function
-- when implementing expand
replaceWord :: String -> KeywordDefs -> String
replaceWord word@('$' : tail) keydefs = x
where
(x : xs) = (lookUp word keydefs)
replaceWord word _ = word
-----------------------------------------------------
-- The provided main program which uses your functions to merge a
-- template and source file.
main :: IO ()
main = do
args <- getArgs
main' args
where
main' :: [String] -> IO ()
main' [template, source, output] = do
t <- readFile template
i <- readFile source
writeFile output (expand t i)
main' _ = putStrLn ("Usage: runghc MP <template> <info> <output>")