Creating lenses
In this recipe, we will look at how we can define a generic property getter and setter. We will write a data type and we will write a generic type that will achieve both getting and setting a field inside the data type.
How to do it...
- Create a new project
creating-lenses
, with asimple
stack template:
stack new creating-lenses simple
- Open
src/Main.hs
. We will be adding our source here. Define theMain
module. Enable extensionRank2Types
before theMain
module. Also, addStandaloneDeriving
andDerivingFunctor
. We will useDerivingFunctor
to automatically derive theFunctor
definition:
{-# LANGUAGE Rank2Types, StandaloneDeriving, DeriveFunctor #-} module Main where
- Define a data type
Point
, which represents a two-dimensional point:
data Point = Point Double Double deriving Show
- Now define a generic structure
s
, and we need to get a field of typea
from the structure. Its type would bes -> a
. Now imagine we need to change some property of structure...