-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchapter-24.hs
436 lines (341 loc) · 10.6 KB
/
chapter-24.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
-- I don't want any warnings as exercises will have some warnings.
{-# OPTIONS_GHC -w #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Chapter_24 where
import Text.Trifecta
import Text.Parser.Combinators
import Control.Applicative
import Data.Ratio ((%), numerator, denominator)
import Data.ByteString (ByteString)
import Data.Char (isAlpha)
import Data.Map (Map)
import qualified Data.Map as M
import Data.Text (Text)
import Test.Hspec
import Text.RawString.QQ
import Data.Attoparsec.Text (parseOnly)
import Data.String (IsString)
stop :: Parser a
stop = unexpected "stop"
one = char '1'
one' = one >> stop
oneTwo = char '1' >> char '2'
oneTwo' = oneTwo >> stop
testParse :: Parser Char -> IO ()
testParse p = print $ parseString p mempty "123"
pNL s = putStrLn ('\n' : s)
main = do
pNL "stop:"
testParse stop
pNL "one:"
testParse one
pNL "one':"
testParse one'
pNL "oneTwo:"
testParse oneTwo
pNL "oneTwo':"
testParse oneTwo'
-- Exercises: Parsing Practice
-- 1
{-
There’s a combinator that’ll let us mark that we expect an input stream to be
finished at a particular point in our parser. In the parsers library this is
simply called eof (end-of-file) and is in the Text.Parser.Combinators
module. See if you can make the one and oneTwo parsers fail because they didn’t
exhaust the input stream!
-}
oneEof = one <* eof
oneTwoEof = oneTwo <* eof
-- 2
{-
Use string to make a Parser that parses “1”, “12”, and “123” out of the example --
input respectively. Try combining it with stop too. That is, a single parser --
should be able to parse all three of those strings. --
-}
oneTwoThree :: Parser String
oneTwoThree = string "123" <|> string "12" <|> string "1" <|> stop
-- 3
-- Try writing a Parser that does what string does, but using char.
stringParser :: String -> Parser String
stringParser = foldr (\c acc -> (:) <$> char c <*> acc) $ return ""
--
badFraction = "1/0"
alsoBad = "10"
shouldWork = "1/2"
shouldAlsoWork = "2/1"
parseFraction :: Parser Rational
parseFraction = do
numerator <- decimal
char '/'
denominator <- decimal
return (numerator % denominator)
main' :: IO ()
main' = do
let parseFraction' = parseString parseFraction mempty
print $ parseFraction' shouldWork
print $ parseFraction' shouldAlsoWork
print $ parseFraction' alsoBad
print $ parseFraction' badFraction
-- Exercise: Unit of Success
{-
This should not be unfamiliar at this point, even if you do not understand all
the details:
Prelude> parseString integer mempty "123abc"
Success 123
Prelude> parseString (integer >> eof) mempty "123abc"
Failure (interactive):1:4: error: expected: digit,
end of input
123abc<EOF>
^
Prelude> parseString (integer >> eof) mempty "123"
Success ()
You may have already deduced why it returns () as a Success result here; it’s
consumed all the input but there is no result to return from having done so. The
result Success () tells you the parse was successful and consumed the entire
input, so there’s nothing to return.
What we want you to try now is rewriting the final example so it returns the
integer that it parsed instead of Success (). It should return the integer
successfully when it receives an input with an integer followed by an EOF and
fail in all other cases:
Prelude> parseString (yourFuncHere) mempty "123"
Success 123
Prelude> parseString (yourFuncHere) mempty "123abc"
Failure (interactive):1:4: error: expected: digit,
end of input
123abc<EOF>
-}
s = parseString (integer <* eof) mempty "123"
f = parseString (integer <* eof) mempty "123abc"
-- Exercise: Try Try
{-
Make a parser, using the existing fraction parser plus a new decimal parser,
that can parse either decimals or fractions. You’ll want to use <|> from
Alternative to combine the...alternative parsers. If you find this too
difficult, write a parser that parses straightforward integers or
fractions. Make a datatype that contains either an integer or a rational and use
that datatype as the result of the parser. Or use Either. Run free, grasshopper.
Hint: we’ve not explained it yet, but you may want to try try.
-}
parseDecimalOrFraction :: Parser (Either Rational Integer)
parseDecimalOrFraction = try (Left <$> parseFraction) <|> (Right <$> decimal)
--
headerEx :: ByteString
headerEx = "[blah]"
-- "[blah]" -> Section "blah"
newtype Header = Header String
deriving (Eq, Ord, Show)
parseBracketPair :: Parser a -> Parser a
parseBracketPair p = char '[' *> p <* char ']'
parseHeader :: Parser Header
parseHeader = parseBracketPair (Header <$> some letter)
--
assignmentEx :: ByteString
assignmentEx = "woot=1"
type Name = String
type Value = String
type Assignments = Map Name Value
parseAssignment :: Parser (Name, Value)
parseAssignment = do
name <- some letter
_ <- char '='
val <- some (noneOf "\n")
skipEOL
return (name, val)
skipEOL :: Parser ()
skipEOL = skipMany $ oneOf "\n"
--
commentEx :: ByteString
commentEx =
"; last modified 1 April\
\ 2001 by John Doe"
commentEx' :: ByteString
commentEx' = "; blah\n; woot\n \n;hah"
skipComments :: Parser ()
skipComments =
skipMany (do _ <- char ';' <|> char '#'
skipMany (noneOf "\n")
skipEOL)
--
sectionEx :: ByteString
sectionEx =
"; ignore me\n[states]\nChris=Texas"
sectionEx' :: ByteString
sectionEx' = [r|
; ignore me
[states]
Chris=Texas
|]
sectionEx'' :: ByteString
sectionEx'' = [r|
; comment
[section]
host=wikipedia.org
alias=claw
[whatisit]
red=intoothandclaw
|]
data Section =
Section Header Assignments
deriving (Eq, Show)
newtype Config =
Config (Map Header Assignments)
deriving (Eq, Show)
skipWhitespace :: Parser ()
skipWhitespace = skipMany $ char ' ' <|> char '\n'
parseSection :: Parser Section
parseSection = do
skipWhitespace
skipComments
h <- parseHeader
skipEOL
assingments <- some parseAssignment
return . Section h $ M.fromList assingments
rollup :: Section -> Map Header Assignments -> Map Header Assignments
rollup (Section h a) = M.insert h a
parseIni :: Parser Config
parseIni = do
sections <- some parseSection
let mapOfSections =
foldr rollup M.empty sections
return $ Config mapOfSections
--
maybeSuccess :: Result a -> Maybe a
maybeSuccess (Success a) = Just a
maybeSuccess _ = Nothing
main'' :: IO ()
main'' = hspec $ do
describe "Assignment Parsing" $
it "can parse a simple assingment" $ do
let m = parseByteString
parseAssignment
mempty
assignmentEx
r' = maybeSuccess m
print m
r' `shouldBe` Just ("woot", "1")
describe "Header Parsing" $
it "can parse a simple header" $ do
let m = parseByteString
parseHeader
mempty
headerEx
r' = maybeSuccess m
print m
r' `shouldBe` Just (Header "blah")
describe "Comment parsing" $
it "Skips comment before header" $ do
let p = skipComments >> parseHeader
i = "; woot\n[blah]"
m = parseByteString p mempty i
r' = maybeSuccess m
print m
r' `shouldBe` Just (Header "blah")
describe "Section parsing" $
it "can parse a simple section" $ do
let m = parseByteString parseSection mempty sectionEx
r' = maybeSuccess m
states = M.fromList [("Chris", "Texas")]
expected' =Just (Section (Header "states") states)
print m
r' `shouldBe` expected'
describe "INI parsing" $
it "Can parse multiple sections" $ do
let m = parseByteString parseIni mempty sectionEx''
r' = maybeSuccess m
sectionValues = M.fromList [ ("alias", "claw")
, ("host", "wikipedia.org")]
whatisitValues = M.fromList [("red", "intoothandclaw")]
expected' = Just (Config (M.fromList
[ (Header "section" , sectionValues)
, (Header "whatisit" , whatisitValues)]))
print m
r' `shouldBe` expected'
--
p' :: Parser [Integer]
p' = some $ do
i <- token $ some digit
return $ read i
--
badFraction' :: IsString s => s
badFraction' = "1/0"
alsoBad' :: IsString s => s
alsoBad' = "10"
shouldWork' :: IsString s => s
shouldWork' = "1/2"
shouldAlsoWork' :: IsString s => s
shouldAlsoWork' = "2/1"
parseFraction' :: (Monad m, MonadFail m, TokenParsing m) => m Rational
parseFraction' = do
numerator <- decimal
_ <- char '/'
denominator <- decimal
case denominator of
0 -> fail "Denominator cannot be zero"
_ -> return $ numerator % denominator
main''' :: IO ()
main''' = do
-- parseOnly is Attoparsec
let attoP = parseOnly parseFraction'
print $ attoP badFraction'
print $ attoP shouldWork'
print $ attoP shouldAlsoWork'
print $ attoP alsoBad'
-- parseString is Text.Trifecta
let p f i = parseString f mempty i
print $ p parseFraction' badFraction'
print $ p parseFraction' shouldWork'
print $ p parseFraction' shouldAlsoWork'
print $ p parseFraction' alsoBad'
-- Chapter Exercises
-- 1
{-
Write a parser for semantic versions as defined by http://semver.org/. After
making a working parser, write an Ord instance for the SemVer type that obeys
the specification outlined on the SemVer website.
-}
data NumberOrString =
NOSS String
| NOSI Integer
deriving (Eq, Show)
type Major = Integer
type Minor = Integer
type Patch = Integer
type Release = [NumberOrString]
type Metadata = [NumberOrString]
data SemVer = SemVer Major Minor Patch Release Metadata
deriving (Show, Eq)
parseMetadata :: Parser Metadata
parseMetadata = char '+' *> sepBy1 parseNumberOrString (char '.')
parsePreRelease :: Parser Release
parsePreRelease = char '-' *> sepBy1 parseNumberOrString (char '.')
parseNumberOrString :: Parser NumberOrString
parseNumberOrString =
(NOSI <$> integer)
<|> (NOSS <$> some letter)
<|> (NOSS <$> some (char '-'))
parseSemver :: Parser SemVer
parseSemver = do
major <- integer
_ <- char '.'
minor <- integer
_ <- char '.'
patch <- integer
release <- option [] parsePreRelease
metadata <- option [] parseMetadata
eof
return $ SemVer major minor patch release metadata
instance Ord NumberOrString where
compare (NOSI _) (NOSS _) = LT
compare (NOSS _) (NOSI _) = GT
compare (NOSI x) (NOSI y) = compare x y
compare (NOSS x) (NOSS y) = compare x y
instance Ord SemVer where
compare (SemVer major minor patch release _) (SemVer major' minor' patch' release' _)
| major /= major' = compare major major'
| minor /= minor' = compare minor minor'
| patch /= patch' = compare patch patch'
| null release && null release' = EQ
| null release = GT
| null release' = LT
| otherwise = compare release release'