Skip to content

Instantly share code, notes, and snippets.

@cacharle
Created September 5, 2019 18:43
Show Gist options
  • Save cacharle/9fa1cba7488f96f93dda7fd6acd26d02 to your computer and use it in GitHub Desktop.
Save cacharle/9fa1cba7488f96f93dda7fd6acd26d02 to your computer and use it in GitHub Desktop.
-- 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