Skip to content

Instantly share code, notes, and snippets.

@pjanik
Last active November 23, 2015 19:39
Show Gist options
  • Save pjanik/011a8fa8633748c3d2e9 to your computer and use it in GitHub Desktop.
Save pjanik/011a8fa8633748c3d2e9 to your computer and use it in GitHub Desktop.
main = do
print $ (rpn "1 2 + 10 * 13 52 - 12 /")
rpn :: (Read a, Fractional a) => String -> a
rpn input = rpnProcess (words input) []
rpnProcess :: (Read a, Fractional a) => [String] -> [a] -> a
rpnProcess [] stack = head stack
rpnProcess (x:inputTail) stack = if x `elem` ["+", "-", "*", "/"] then
rpnProcess inputTail (action x stack)
else
rpnProcess inputTail ((read x):stack)
action :: (Read a, Fractional a) => String -> [a] -> [a]
action "+" (a:b:tail) = (a + b):tail
action "-" (a:b:tail) = (a - b):tail
action "*" (a:b:tail) = (a * b):tail
action "/" (a:b:tail) = (a / b):tail
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment