Skip to content

Instantly share code, notes, and snippets.

@MiyamonY
Created March 6, 2015 09:28
Show Gist options
  • Save MiyamonY/e7e1b1814d2555752278 to your computer and use it in GitHub Desktop.
Save MiyamonY/e7e1b1814d2555752278 to your computer and use it in GitHub Desktop.
haskell monad porland
import Control.Monad
import Data.List
import Test.HUnit
readMaybe :: (Read a) => String -> Maybe a
readMaybe st = case reads st of [(x, "")] -> Just x
_ -> Nothing
foldingFunction :: [Double] -> String -> Maybe [Double]
foldingFunction (x:y:ys) "*" = return $ (y * x) : ys
foldingFunction (x:y:ys) "+" = return $ (y + x) : ys
foldingFunction (x:y:ys) "-" = return $ (y - x) : ys
foldingFunction xs numberString = liftM (:xs) (readMaybe numberString)
tests1 :: Test
tests1 =
let stack = [1.0, 2.0]
t = foldingFunction
in
"foldinfFunction" ~:
["test1" ~: (t stack "*") ~?= Just [2.0],
"test2" ~: (t stack "+") ~?= Just [3.0],
"test3" ~: (t stack "-") ~?= Just [1.0],
"test4" ~: (t stack "3") ~?= Just [3.0, 1.0, 2.0],
"test5" ~: (t stack "aawaw") ~?= Nothing
]
solveRPN :: String -> Maybe Double
solveRPN st = do
[result] <- foldM foldingFunction [] $ words st
return result
tests2 :: Test
tests2 =
let t = solveRPN in
"solveRPN" ~:
["test1" ~: (t "aaa") ~?= Nothing,
"test2" ~: (t "1 2 +") ~?= Just 3.0,
"test3" ~: (t "1 2 + 3 *") ~?= Just 9.0
]
main :: IO ()
main = do
runTestTT $ TestList [tests1, tests2]
return ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment