Skip to content

Instantly share code, notes, and snippets.

@monzou
Created July 8, 2012 06:10
Show Gist options
  • Save monzou/3069624 to your computer and use it in GitHub Desktop.
Save monzou/3069624 to your computer and use it in GitHub Desktop.
import Control.Monad.State
--
-- 普通に Stack
--
type Stack = [Int]
pop :: Stack -> (Int, Stack)
pop (x:xs) = (x, xs)
push :: Int -> Stack -> ((), Stack)
push a xs = ((), a:xs)
stackOp :: Stack -> (Int, Stack)
stackOp stack = let
((), newStack1) = push 3 stack
(a, newStack2) = pop newStack1
in pop newStack2
--
-- Monad.State を使って Stack
--
type MonadStack = [Int]
mpop :: State MonadStack Int
mpop = state $ \(x:xs) -> (x, xs)
mpush :: Int -> State MonadStack ()
mpush a = state $ \xs -> ((), a:xs)
-- Monad を使うと綺麗に表現できる
monadStackOp :: State Stack Int
monadStackOp = do
mpush 3
a <- mpop
if a == 5
then mpush 5
else do
mpush 3
mpush 8
mpop
main = do
print $ stackOp [5, 8, 2, 1] -- (5, [8, 2, 1])
print $ runState monadStackOp [5, 8, 2, 1] -- (8, [3, 5, 8, 2, 1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment