-
-
Save pasberth/6349251 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE TemplateHaskell #-} | |
import Control.Lens | |
-- 基本となるオブジェクト | |
data Obj = Obj { | |
_pos :: Int | |
} deriving (Show) | |
-- Obj型のオブジェクトをもつ抽象的なクラスHasObjを作る | |
makeClassy ''Obj | |
data Ball = Ball { | |
_objBall :: Obj, | |
_r :: Int | |
} deriving (Show) | |
makeLenses ''Ball | |
-- BallはObj型のobjBallをもつのでHasObjのインスタンスになる | |
instance HasObj Ball where | |
obj = objBall | |
data Bar = Bar { | |
_objBar :: Obj, | |
_width :: Int | |
} deriving (Show) | |
makeLenses ''Bar | |
instance HasObj Bar where | |
obj = objBar | |
-- HasObjのインスタンスになったオブジェクトならなんでもこの函数で操作できる | |
updatePos :: (HasObj c) => c -> c | |
updatePos = (obj . pos) %~ (+2) | |
main :: IO () | |
main = do | |
let a = Obj 10 | |
print $ updatePos a | |
-- output: Obj {_pos = 12} | |
let b = Ball (Obj 10) 5 | |
print $ updatePos b | |
-- output: Ball {_objBall = Obj {_pos = 12}, _r = 5} | |
let c = Bar (Obj 10) 100 | |
print $ updatePos c | |
-- output: Bar {_objBar = Obj {_pos = 12}, _width = 100} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment