Skip to content

Instantly share code, notes, and snippets.

@jehugaleahsa
Created March 3, 2018 19:40
Show Gist options
  • Save jehugaleahsa/25bdac77d8f260c9ae602ca40359e30d to your computer and use it in GitHub Desktop.
Save jehugaleahsa/25bdac77d8f260c9ae602ca40359e30d to your computer and use it in GitHub Desktop.
Reverse Polish Notation
calculate :: [String] -> Maybe Double
calculate [] = Nothing
calculate a = calculateHelper a []
where
calculateHelper [] [a] = Just a
calculateHelper ("+":items) (x:y:rest) = calculateHelper items ((y+x):rest)
calculateHelper ("-":items) (x:y:rest) = calculateHelper items ((y-x):rest)
calculateHelper ("*":items) (x:y:rest) = calculateHelper items ((y*x):rest)
calculateHelper ("/":items) (x:y:rest) = calculateHelper items ((y/x):rest)
calculateHelper (a:items) rest = case (readMaybe a :: Maybe Double) of
Just a -> calculateHelper items (a:rest)
Nothing -> Nothing
calculateHelper _ _ = Nothing
parts = words "10 4 3 + 2 * -"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment