module StackMachine where import System.IO type Transition state input output = (state, input) -> (state, output) process :: Transition state input output -> state -> [input] -> [output] process tr s [] = [] process tr s (input : inputs) = let (s', output) = tr (s, input) in output : process tr s' inputs runprocess :: Transition state String String -> state -> IO () runprocess tr s = do hSetBuffering stdout LineBuffering -- requires: ``import System.IO'' at beginning of module interact (unlines . process tr s . lines) countEcho :: Transition Integer String String countEcho (count,input) = (count', shows count' (' ' : input)) where count' = succ count trAdd :: Transition Integer String String trAdd (s,input) = (s', show s') where n = read input s' = s + n polish :: Transition [Integer] String String polish (n : m : ks, "+") = (k : ks, show k) where k = m + n polish (n : m : ks, "-") = (k : ks, show k) where k = m - n polish (n : m : ks, "*") = (k : ks, show k) where k = m * n polish (n : m : ks, "/") = (k : ks, show k) where k = m `div` n polish (ks , input) = (k : ks, show k) where k = read input