Skip to content

Instantly share code, notes, and snippets.

@MiyamonY
Created March 6, 2015 04:26
Show Gist options
  • Save MiyamonY/bc967e349c72369273a1 to your computer and use it in GitHub Desktop.
Save MiyamonY/bc967e349c72369273a1 to your computer and use it in GitHub Desktop.
haskell monadic function
import Test.HUnit
import Control.Monad
import Control.Monad.Writer
import qualified Control.Monad.State as S
import StateStack
import Control.Applicative
tests = ["liftM1" ~: (liftM (*3) $ Just 8) ~?= Just 24,
"liftM2" ~: (return 8 >>= \ x -> Just $ (*3) x) ~?= Just 24,
"fmap" ~: (fmap (*3) $ Just 8) ~?= Just 24,
"liftM2" ~: (runWriter $ liftM not $ writer (True, "chickpeas")) ~?= (False, "chickpeas"),
"listM3" ~: (S.runState $ liftM (+100) pop) [1,2,3,4] ~?= (101, [2,3,4]),
"listM4" ~: (S.runState $ fmap (+100) pop) [1,2,3,4] ~?= (101, [2,3,4]),
"AppFun1" ~: ((+) <$> Just 3 <*> Just 5) ~?= Just 8, -- applicative functor
"AppFun2" ~: ((+) <$> Just 3 <*> Nothing) ~?= Nothing,
"Fun" ~: (fmap (+ 3) $ Just 5) ~?= Just 8,
"AppFun3" ~: (Just (+3) <*> Just 4) ~?= Just 7,
"AppFun4" ~: (Just (+3) `ap` Just 4) ~?= Just 7,
"AppFun5" ~: [(+1), (+2), (+3)] `ap` [10, 11] ~?= [11,12,12,13,13,14],
"join1" ~: (join $ Just (Just 9)) ~?= Just 9,
"join2" ~: (join $ Just (Nothing :: Maybe Int)) ~?= Nothing,
"join3" ~: (join (Nothing :: Maybe (Maybe Int))) ~?= Nothing,
"join4" ~: (join [[1,2,3],[4,5,6]]) ~?= [1..6],
"join5" ~: (runWriter . join . writer $ (writer (1, "aaa"), "bbb")) ~?=
(1, "bbbaaa"),
"join6" ~: ((join $ (Right (Right 9))) :: Either String Int) ~?= Right 9,
"join7" ~: ((join $ Right (Left "error")) :: Either String Int) ~?= Left "error"
-- "join8" ~: (S.runState . join . S.state (\ s -> (push 10, 1:2:s)) $ [0, 0, 0])
-- ~?= ((), [10, 1, 2, 0, 0, 0])
]
runTests = do
runTestTT $ TestList tests
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment