Skip to content

Instantly share code, notes, and snippets.

@apstndb
Last active December 11, 2015 09:58
Show Gist options
  • Save apstndb/4583134 to your computer and use it in GitHub Desktop.
Save apstndb/4583134 to your computer and use it in GitHub Desktop.
第7回 スタートHaskell2演習問題「Stateモナドを使ってみよう」解答 http://wiki.haskell.jp/Workshop/StartHaskell2/exercise14
import Control.Monad.State
type Point = (Int, Int)
move :: Char -> State Point ()
move 'u' = do (x,y) <- get; put (x, y-1) -- 上へ移動
move 'd' = do (x,y) <- get; put (x, y+1) -- 下へ移動
move 'l' = do (x,y) <- get; put (x-1, y) -- 左へ移動
move 'r' = do (x,y) <- get; put (x+1, y) -- 右へ移動
-- Stateの更新はmodify を使った方がきれいに書ける?
-- modX :: (Int -> Int) -> Point -> Point
-- modY :: (Int -> Int) -> Point -> Point
-- modX f (x, y) = (f x, y)
-- modY f (x, y) = ( x, f y)
-- 単項のマイナスはセクションにならない http://www.haskell.org/haskellwiki/Unary_minus
-- move 'u' = modify $ modY (subtract 1) -- 上へ移動
-- move 'd' = modify $ modY (+1) -- 下へ移動
-- move 'l' = modify $ modX (subtract 1) -- 左へ移動
-- move 'r' = modify $ modX (+1) -- 右へ移動
moveGame :: String -> State Point ()
moveGame [] = return ()
moveGame (c:cs) = do
move c
moveGame cs
main :: IO ()
main = print $ execState (moveGame "ulrdddlr") (0,0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment