Create a gist now

Instantly share code, notes, and snippets.

Overloading records with lens
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE FlexibleInstances #-}
module Fields where
import Control.Lens
import Control.Lens.TH
data Vec2 = Vec2
{ _vec2X :: Double
, _vec2Y :: Double
} deriving (Eq, Read, Show)
data Vec3 = Vec3
{ _vec3X :: Double
, _vec3Y :: Double
, _vec3Z :: Double
} deriving (Eq, Read, Show)
makeFields ''Vec2
makeFields ''Vec3
-- results in: Vec2 2 2
example1 = over x (+1) $ Vec2 1 2
-- results in: Vec3 1 2 300
example2 = over z (*100) $ Vec3 1 2 3
-- | 2- and 3-Tuple instances for x and y.
instance HasX (Double, a) Double where
x = _1
instance HasY (a, Double) Double where
y = _2
instance HasX (Double, a, b) Double where
x = _1
instance HasY (a, Double, b) Double where
y = _2
instance HasZ (a, b, Double) Double where
z = _3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment