Skip to content

Instantly share code, notes, and snippets.

@pasberth
Forked from myuon/makeClassy.hs
Created August 27, 2013 03:10
Show Gist options
  • Save pasberth/6349251 to your computer and use it in GitHub Desktop.
Save pasberth/6349251 to your computer and use it in GitHub Desktop.
{-# 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