Skip to content

Instantly share code, notes, and snippets.

@prednaz
Last active January 26, 2021 00:13
Show Gist options
  • Save prednaz/6e8d30b8b100b47f79d0e72b90d740d1 to your computer and use it in GitHub Desktop.
Save prednaz/6e8d30b8b100b47f79d0e72b90d740d1 to your computer and use it in GitHub Desktop.
{-# language
FlexibleInstances,
MultiParamTypeClasses,
OverloadedLabels,
DuplicateRecordFields,
DataKinds,
UndecidableInstances,
TypeFamilies,
TemplateHaskell
#-}
import Optics
data Position =
Position
{
x :: Double,
y :: Double
}
makeFieldLabelsWith noPrefixFieldLabels ''Position
data Tile =
Empty {position :: Position} |
Wall {position :: Position}
makeFieldLabelsWith noPrefixFieldLabels ''Tile
tiles :: [Tile]
tiles =
[Wall (Position 0 0), Wall (Position 0 1), Wall (Position 0 2)]
tilesFiltered r =
[tile |
tile <- tiles,
((tile ^. #position % #x) ** 2 + (tile ^. #position % #y) ** 2) ** (1/2) < r
]
-- more examples of Optics API follow
tileSample :: Tile
tileSample = Wall (Position 2 1)
tileSamplePosition1 :: Position
tileSamplePosition1 = tileSample ^. #position -- == Position 2 1
tileSampleX1 :: Double
tileSampleX1 = tileSample ^. #position % #x -- == 2
-- `view` is an alternative to `^.`
tileSamplePosition2 :: Position
tileSamplePosition2 = view #position tileSample -- == Position 2 1
tileSampleX2 :: Double
tileSampleX2 = view (#position % #x) tileSample -- == 2
tileSampleUpdated :: Tile
tileSampleUpdated = set (#position % #x) 1 tileSample -- == Wall (Position 1 1)
tileSampleTranslated :: Tile
tileSampleTranslated = over (#position % #x) (+1) tileSample -- == Wall (Position 3 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment