Skip to content

Instantly share code, notes, and snippets.

@shigemk2
Created July 20, 2015 07:22
Show Gist options
  • Select an option

  • Save shigemk2/2a2377e84b1010d0d33a to your computer and use it in GitHub Desktop.

Select an option

Save shigemk2/2a2377e84b1010d0d33a to your computer and use it in GitHub Desktop.
import Data.List.Split
import Control.Monad.State
rpn str = rpnPrime (splitOn " " str) []
rpnPrime ("+":t) (y:x:zs) = rpnPrime t $ x + y:zs
rpnPrime (n:t) zs = rpnPrime t $ read n:zs
rpnPrime [] [x] = x
rpnM str = evalState (rpnPrimeM $ splitOn " " str) []
rpnPrimeM :: [String] -> State [Int] Int
rpnPrimeM ("+":t) = do
(y:x:zs) <- get
put $ x + y:zs
rpnPrimeM t
rpnPrimeM (n:t) = do
zs <- get
put $ read n:zs
rpnPrimeM t
rpnPrimeM [] = do
[x] <- get
return x
main = do
print $ rpnM "1"
print $ rpnM "1 2 +"
print $ rpnM "1 2 3 + +"
print $ rpnM "1 2 + 3 +"
print $ rpnM "1 2 + 3 4 + +"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment