Skip to content

Instantly share code, notes, and snippets.

@jehugaleahsa jehugaleahsa/rpn.hs
Created Mar 3, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.