-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtokenize.hs
34 lines (25 loc) · 1023 Bytes
/
tokenize.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
module Tokenize where
import Data.Char (isDigit)
import Token
sanitizeDecimal str = let (beforeDecimal, afterDecimal) = span (/='.') str
in (formatInteger beforeDecimal) ++ "." ++ (formatFractional afterDecimal)
where
formatInteger [] = "0"
formatInteger x = x
formatFractional [] = "0"
formatFractional xs = (if length xs > 1 then (drop 1 xs) else "0")
str2FloatToken = FloatToken . read . sanitizeDecimal
tokenize :: String -> [Token]
tokenize [] = []
tokenize (' ':xs) = tokenize xs
tokenize str@(x:_)
| isPartOfNumber x =
let (numbers, rest) = span isPartOfNumber str in (str2FloatToken numbers) : tokenize rest
where isPartOfNumber y = (y == '.') || isDigit y
tokenize ('+':xs) = OpToken '+' : tokenize xs
tokenize ('-':xs) = OpToken '-' : tokenize xs
tokenize ('/':xs) = OpToken '/' : tokenize xs
tokenize ('*':xs) = OpToken '*' : tokenize xs
tokenize ('^':xs) = OpToken '^' : tokenize xs
tokenize ('(':xs) = LeftParen : tokenize xs
tokenize (')':xs) = RightParen : tokenize xs