--First Edition. Need to rewrite to include lexer then parser to implement brackets
import Control.Arrow
splitAtFirst :: Eq a => a -> [a] -> ([a], [a])
splitAtFirst x = (id *** drop 1) . break (x ==)
toFloat :: String -> Float
toFloat x = read x :: Float
parseInputs :: (String,String) -> String -> Float
parseInputs (a,b) op | op == "+" = (parseInput a) + (parseInput b)
| op == "-" = (parseInput a) - (parseInput b)
| op == "*" = (parseInput a) * (parseInput b)
| op == "/" = (parseInput a) / (parseInput b)
| op == "^" = (parseInput a) ** (parseInput b)
parseInput :: String -> Float
parseInput xs | '+' `elem` xs = parseInputs (splitAtFirst '+' xs) "+"
| '-' `elem` xs = parseInputs (splitAtFirst '-' xs) "-"
| '*' `elem` xs = parseInputs (splitAtFirst '*' xs) "*"
| '/' `elem` xs = parseInputs (splitAtFirst '/' xs) "/"
| '^' `elem` xs = parseInputs (splitAtFirst '^' xs) "^"
| otherwise = toFloat xs
main = do
print(parseInput "1+2+3+4")
print(parseInput "3-2")
print(parseInput "3*2")
print(parseInput "10/5")
print(parseInput "2+1*3-1")
print(parseInput "3-4/2")
print(parseInput "3^2")
print(parseInput "2^2+1")
Lexer:
String -> [Token]
Parser:
[Token] -> SyntaxTree
SyntaxTree -> FinalExpression (Float)
Example: "1*(2+3/(5-4))" => 1,*,(,2,+,3,/,(,5,-,4,),) or 1,*,(2,+,3,/,(5,-,4))