Created
May 15, 2011 17:20
-
-
Save khayrov/973332 to your computer and use it in GitHub Desktop.
very simple expression parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
expr :: String -> (Double, String) | |
expr s = expr1 x rest where (x, rest) = term s | |
expr1 lhs ('+' : s) = expr1 (lhs + x) rest where (x, rest) = term s | |
expr1 lhs ('-' : s) = expr1 (lhs - x) rest where (x, rest) = term s | |
expr1 lhs s = (lhs, s) | |
term s = term1 x rest where (x, rest) = factor s | |
term1 lhs ('*' : s) = term1 (lhs * x) rest where (x, rest) = factor s | |
term1 lhs ('/' : s) = term1 (lhs / x) rest where (x, rest) = factor s | |
term1 lhs s = (lhs, s) | |
factor ('(' : s) = (x, rest) where (x, ')' : rest) = expr s | |
factor s = head $ reads s | |
eval s = x where (x, "") = expr s | |
main = getLine >>= print . eval |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment