Skip to content

Instantly share code, notes, and snippets.

@tokiwoousaka
Created December 26, 2014 06:04
Show Gist options
  • Save tokiwoousaka/273f865dd9f0e3a94a22 to your computer and use it in GitHub Desktop.
Save tokiwoousaka/273f865dd9f0e3a94a22 to your computer and use it in GitHub Desktop.
{-# LANGUAGE TemplateHaskell #-}
module Main where
import Control.Monad.State
import Control.Lens
data Point = Point
{ _pointX :: Int
, _pointY :: Int
} deriving Show
data Size = Size
{ _height :: Int
, _width :: Int
} deriving Show
data Object = Object
{ _name :: String
, _position :: Point
, _size :: Size
} deriving Show
----
-- アクセッサをマクロで自動生成
-- アクセッサの型: forall f. Functor f => (a -> f b) -> s -> f t
makeLenses ''Point
makeLenses ''Size
makeLenses ''Object
----
sampleObject :: Object
sampleObject = Object
{ _name = "sample"
, _position = Point
{ _pointX = 100
, _pointY = 200
}
, _size = Size
{ _height = 300
, _width = 400
}
}
-- 手続きは次の2種類の演算で構成される
-- return :: a -> m a
-- bind :: m a -> (a -> m b) -> m b
-- 状態(副作用)の計算を次の型で表せる
-- s -> (a, s)
sampleProc :: State Object ()
sampleProc = do
name .= "new name"
position.pointX += 100
size.width .= 500
----
main :: IO ()
main = do
putStrLn "処理前"
print sampleObject
putStrLn "処理後"
print $ execState sampleProc sampleObject
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment