Created
September 5, 2019 18:43
-
-
Save cacharle/9fa1cba7488f96f93dda7fd6acd26d02 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
-- Reverse Polish Notation parser | |
-- from: http://learnyouahaskell.com/functionally-solving-problems | |
rpn :: String -> Float | |
rpn expr = head $ foldl foldFunc [] (words expr) | |
where foldFunc acc op | |
| head op `elem` ['1'..'9'] = (read op :: Float) : acc | |
| otherwise = applyOp op (acc !! 1) (head acc) : drop 2 acc | |
applyOp op a b = case op of "+" -> a + b | |
"-" -> a - b | |
"*" -> a * b | |
"/" -> a / b | |
-- original | |
rpn' :: String -> Float | |
rpn' = head . foldl parse [] . words | |
where parse (x : y : acc) "+" = y + x : acc | |
parse (x : y : acc) "-" = y - x : acc | |
parse (x : y : acc) "*" = y * x : acc | |
parse (x : y : acc) "/" = y / x : acc | |
parse (x : y : acc) "^" = y ** x : acc | |
parse (x : acc) "ln" = log x : acc | |
parse acc "sum" = [sum acc] | |
parse acc n = (read n :: Float) : acc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment