Skip to content

Instantly share code, notes, and snippets.

@kgadek
Created March 12, 2014 17:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kgadek/9512169 to your computer and use it in GitHub Desktop.
Save kgadek/9512169 to your computer and use it in GitHub Desktop.
I can into simple Lenses!
{-# LANGUAGE ExistentialQuantification #-}
data Point = Point { x :: Int, y :: Int } deriving (Show)
data Rect = Rect { a :: Point, b :: Point, c :: Point, d :: Point } deriving (Show)
data Lens s a = Lens { get :: s -> a, set :: s -> a -> s}
getA :: Rect -> Point
getA = a
setA :: Rect -> Point -> Rect
setA (Rect a b c d) a' = Rect a' b c d
lensA :: Lens Rect Point
lensA = Lens getA setA
getX :: Point -> Int
getX = x
setX :: Point -> Int -> Point
setX (Point x y) x' = Point x' y
lensX :: Lens Point Int
lensX = Lens getX setX
cl :: Lens c b -> Lens b a -> Lens c a
cl (Lens getB setB) (Lens getA setA) = Lens get set
where
get = getA . getB
set c = setB c . setA (getB c)
lensAX = cl lensA lensX
setl :: s -> Lens s a -> a -> s
setl s (Lens _ set') = set' s
r1 = Rect (Point 0 0) (Point 1 0) (Point 1 1) (Point 0 1)
r2 = setl r1 lensAX 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment