Haskell Language Lens Lenses for records


Example

Simple record

{-# LANGUAGE TemplateHaskell #-}
import Control.Lens

data Point = Point {
    _x :: Float,
    _y :: Float
}
makeLenses ''Point

Lenses x and y are created.

let p = Point 5.0 6.0 
p ^. x     -- returns 5.0
set x 10 p -- returns Point { _x = 10.0, _y = 6.0 }
p & x +~ 1 -- returns Point { _x = 6.0, _y = 6.0 }

Managing records with repeating fields names

data Person = Person { _personName :: String }
makeFields ''Person

Creates a type class HasName, lens name for Person, and makes Person an instance of HasName. Subsequent records will be added to the class as well:

data Entity = Entity { _entityName :: String }
makeFields ''Entity

The Template Haskell extension is required for makeFields to work. Technically, it's entirely possible to create the lenses made this way via other means, e.g. by hand.