-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathExamples.purs
More file actions
232 lines (197 loc) · 8.31 KB
/
Examples.purs
File metadata and controls
232 lines (197 loc) · 8.31 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
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
module Text.Parsing.StringParser.Examples where
import Prelude hiding (between)
import Control.Alt ((<|>))
import Data.Either (Either(..))
import Data.Foldable (fold, foldl, sum)
import Data.List.Types (NonEmptyList)
import Effect (Effect)
import Effect.Console (log, logShow)
import Text.Parsing.StringParser (Parser, fail, runParser, unParser)
import Text.Parsing.StringParser.CodeUnits (anyChar, char, eof, regex, skipSpaces, string)
import Text.Parsing.StringParser.Combinators (between, endBy1, lookAhead, many, many1, sepBy1, (<?>))
-- Serves only to make this file runnable
main :: Effect Unit
main = printResults
printResults :: Effect Unit
printResults = do
log "" -- empty blank line to separate output from function call
log "### Example Content 1 ###"
doBoth "fail" ((fail "example failure message") :: Parser Unit) exampleContent1
doBoth "numberOfAs" numberOfAs exampleContent1
doBoth "removePunctuation" removePunctuation exampleContent1
doBoth "replaceVowelsWithUnderscore" replaceVowelsWithUnderscore exampleContent1
doBoth "tokenizeContentBySpaceChars" tokenizeContentBySpaceChars exampleContent1
doBoth "extractWords" extractWords exampleContent1
doBoth "badExtractWords" badExtractWords exampleContent1
doBoth "quotedLetterExists" quotedLetterExists exampleContent1
log "\n\
\### Example Content 2 ###"
doBoth "parseCSV" parseCSV exampleContent2
-- Example Content 1
exampleContent1 :: String
exampleContent1 =
"How many 'a's are in this sentence, you ask? Not that many."
numberOfAs :: Parser Int
numberOfAs = do
let
oneIfA = 1 <$ string "a" <?> "Letter was 'a'"
zeroIfNotA = 0 <$ regex "[^a]" <?> "Letter was not 'a'"
letterIsOneOrZero = oneIfA <|> zeroIfNotA <?>
"The impossible happened: \
\a letter was not 'a', and was not not-'a'."
convertLettersToList = many1 letterIsOneOrZero
{-
list <- convertLettersToList -}
list <- many1
( (1 <$ string "a")
<|> (0 <$ regex "[^a]")
)
-- calculate total number by adding Ints in list together
pure $ sum list
removePunctuation :: Parser String
removePunctuation = do {-
let
charsAndSpaces = regex "[a-zA-Z ]+"
everythingElse = regex "[^a-zA-Z ]+"
ignoreEverythingElse = "" <$ everythingElse
zeroOrMoreFragments = many1 $ charsAndSpaces <|> ignoreEverythingElse -}
list <- many1
( regex "[a-zA-Z ]+"
<|> ("" <$ regex "[^a-zA-Z ]+" )
)
-- combine the list's contents together via '<>'
pure $ foldl (<>) "" list
replaceVowelsWithUnderscore :: Parser String
replaceVowelsWithUnderscore = do
list <- many1 $ ( ( "_" <$ regex "[aeiou]")
<|> regex "[^aeiou]+"
)
pure $ foldl (<>) "" list
tokenizeContentBySpaceChars :: Parser (NonEmptyList String)
tokenizeContentBySpaceChars = do
(regex "[^ ]+") `sepBy1` (string " ")
extractWords :: Parser (NonEmptyList String)
extractWords = do
endBy1 (regex "[a-zA-Z]+")
-- try commenting out one of the "<|> string ..." lines and see what happens
(many1 ( string " " <?> "Failed to match space as a separator"
<|> string "'" <?> "Failed to match single-quote char as a separator"
<|> string "," <?> "Failed to match comma as a separator"
<|> string "?" <?> "Failed to match question mark as a separator"
<|> string "." <?> "Failed to match period as a separator"
<?> "Could not find a character that separated the content..."
)
)
badExtractWords :: Parser (NonEmptyList String)
badExtractWords = do
list <- endBy1 (regex "[a-zA-Z]+")
-- try commenting out the below "<|> string ..." lines
(many1 ( string " " <?> "Failed to match space as a separator"
<|> string "'" <?> "Failed to match single-quote char as a separator"
<|> string "," <?> "Failed to match comma as a separator"
-- <|> string "?" <?> "Failed to match question mark as a separator"
-- <|> string "." <?> "Failed to match period as a separator"
<?> "Could not find a character that separated the content..."
)
)
-- short for 'end of file' or 'end of content'
eof <?> "Entire content should have been parsed but wasn't."
pure list
-- there are better ways of doing this using `whileM`, but this explains
-- the basic idea:
quotedLetterExists :: Parser Boolean
quotedLetterExists = do
let
singleQuoteChar = string "'"
betweenSingleQuotes parser =
between singleQuoteChar singleQuoteChar parser
list <- many ( true <$ (betweenSingleQuotes (char 'a') <?> "No 'a' found.")
<|> false <$ anyChar
)
pure $ foldl (||) false list
-- Example Content 2
-- CSV sample with some inconsistent spacing
exampleContent2 :: String
exampleContent2 =
"ID, FirstName, LastName, Age, Email\n\
\523, Mark, Kenderson, 24, my.name.is.mark@mark.mark.com\n"
type CsvContent =
{ idNumber :: String
, firstName :: String
, lastName :: String
, age :: String
, originalEmail :: String
, modifiedEmail :: String
}
parseCSV :: Parser CsvContent
parseCSV = do
let
commaThenSpaces = string "," *> skipSpaces
idNumber_ = string "ID"
firstName_ = string "FirstName"
lastName_ = string "LastName"
age_ = string "Age"
email_ = string "Email"
newline = string "\n"
csvColumn = regex "[^,]+"
-- parse headers but don't produce output
void $ idNumber_ *> commaThenSpaces *>
firstName_ *> commaThenSpaces *>
lastName_ *> commaThenSpaces *>
age_ *> commaThenSpaces *>
email_
void newline
-- now we're on line 2
idNumber <- csvColumn <* commaThenSpaces
firstName <- csvColumn <* commaThenSpaces
lastName <- csvColumn <* commaThenSpaces
age <- csvColumn <* commaThenSpaces
-- lookAhead will parse the content ahead of us,
-- then reset the position of the string
-- to what it was before it.
originalEmail <- lookAhead $ regex "[^\n]+"
let
parseAlphanumericChars = regex "[a-zA-Z0-9]+"
parsePeriodsAndPlusesAsEmptyStrings =
"" <$ ((string ".") <|> (string "+"))
parseListOfParts =
many1 ( parseAlphanumericChars
<|> parsePeriodsAndPlusesAsEmptyStrings
)
usernameWithoutPeriodsOrPluses <- fold <$> parseListOfParts
void $ string "@"
domainName <- fold <$> (many1 ((regex "[a-zA-Z0-9]+") <|> (string ".")))
void $ string "\n"
-- Ensure we hit the end of the string content via 'end-of-file'
void eof
-- now return the parsed content
pure { idNumber, firstName, lastName, age, originalEmail
, modifiedEmail: usernameWithoutPeriodsOrPluses <> "@" <> domainName
}
-- Helper functions
doBoth :: forall a. Show a => String -> Parser a -> String -> Effect Unit
doBoth parserName parser content = do
doRunParser parserName parser content
doUnParser parserName parser content
-- | Shows the results of calling `unParser`. You typically want to use
-- | this function when writing a parser because it includes other info
-- | to help you debug your code.
doUnParser :: forall a. Show a => String -> Parser a -> String -> Effect Unit
doUnParser parserName parser content = do
log $ "(unParser) Parsing content with '" <> parserName <> "'"
case unParser parser { str: content, pos: 0 } of
Left rec -> log $ "Position: " <> show rec.pos <> "\n\
\Error: " <> show rec.error
Right rec -> log $ "Result was: " <> show rec.result <> "\n\
\Suffix was: " <> show rec.suffix
log "-----"
-- | Shows the results of calling `runParser`. You typically don't want to use
-- | this function when writing a parser because it doesn't help you debug
-- | your code when you write it incorrectly.
doRunParser :: forall a. Show a => String -> Parser a -> String -> Effect Unit
doRunParser parserName parser content = do
log $ "(runParser) Parsing content with '" <> parserName <> "'"
case runParser parser content of
Left error -> logShow error
Right result -> log $ "Result was: " <> show result
log "-----"