Skip to content

Instantly share code, notes, and snippets.

@khayrov
Created May 15, 2011 17:20
Show Gist options
  • Save khayrov/973332 to your computer and use it in GitHub Desktop.
Save khayrov/973332 to your computer and use it in GitHub Desktop.
very simple expression parser
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