-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSchemeParser.hs
executable file
·56 lines (45 loc) · 1.46 KB
/
SchemeParser.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
module SchemeParser (SchemeVal(..),
parseSexp)
where
-- Modified from Jonathan Tang's lispparser package:
-- http://hackage.haskell.org/package/lispparser/
import Text.ParserCombinators.Parsec
data SchemeVal = SchemeAtom String
| SchemeList [SchemeVal]
| SchemeNumber Double
| SchemeBool Bool
| SchemeString String
deriving Show
parseSexp :: String -> Either ParseError SchemeVal
parseSexp s = parse expParser [] s
symbol :: Parser Char
symbol = oneOf "!$%&|*+-/:<=>?@^_~#"
skipSpaces :: Parser ()
skipSpaces = skipMany1 space
parseAtom :: Parser SchemeVal
parseAtom = do
first <- letter <|> symbol
rest <- many (letter <|> digit <|> symbol)
let atom = [first] ++ rest
return $ case atom of
"true" -> SchemeBool True
"false" -> SchemeBool False
otherwise -> SchemeAtom atom
parseNumber :: Parser SchemeVal
parseNumber = fmap (SchemeNumber . read) $ many1 digit
parseString :: Parser SchemeVal
parseString = do
char '"'
str <- many1 (noneOf "\"")
char '"'
return $ SchemeString str
parseList :: Parser SchemeVal
parseList = fmap SchemeList $ sepBy expParser skipSpaces
expParser :: Parser SchemeVal
expParser = parseAtom
<|> parseNumber
<|> parseString
<|> do char '('
list <- (try parseList)
char ')'
return list