feat: Implement Lexer
This commit is contained in:
parent
fffa295d3c
commit
5c2dc50872
1 changed files with 22 additions and 0 deletions
22
app/Lexer.hs
22
app/Lexer.hs
|
|
@ -8,3 +8,25 @@ data Token = Plus
|
|||
| LBrace
|
||||
| RBrace
|
||||
deriving Show
|
||||
|
||||
lex :: String -> [Token]
|
||||
lex source = reverse (lex' source [] (length source))
|
||||
|
||||
lex' :: String -> [Token] -> Int -> [Token]
|
||||
lex' "" tokens _ = tokens
|
||||
lex' (' ':xs) tokens orgLength = lex' xs tokens orgLength
|
||||
lex' (x:xs) tokens orgLength = case x of
|
||||
'+' -> lex' xs (Plus:tokens) orgLength
|
||||
'-' -> lex' xs (Minus:tokens) orgLength
|
||||
'*' -> lex' xs (Multiply:tokens) orgLength
|
||||
'/' -> lex' xs (Divide:tokens) orgLength
|
||||
'(' -> lex' xs (LBrace:tokens) orgLength
|
||||
')' -> lex' xs (RBrace:tokens) orgLength
|
||||
_ -> lexNumbers (x:xs) tokens orgLength
|
||||
|
||||
lexNumbers :: String -> [Token] -> Int -> [Token]
|
||||
lexNumbers (x:xs) tokens orgLength
|
||||
| isDigit x = lex' (dropWhile isDigit (x:xs)) ((Integer(read (takeWhile isDigit (x:xs))::Int)):tokens) orgLength
|
||||
| otherwise = error $ "Syntax error: " ++ [x] ++ " (" ++ show (orgLength - (length (x:xs))) ++ ")"
|
||||
|
||||
isDigit x = x `elem` "0123456789"
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue