-
Notifications
You must be signed in to change notification settings - Fork 5
References Tutorial
A reference is a property accessor. You can think of it as a setter and getter method. For example if you have a point datatype: data Point = Point Double Double
then, you may define references x
and y
to access the two Double
values inside the point. You can use the reference to get their values and also to modify them.
The simplest problem references solve is the problem of handling a large nested data structure. For example, take the following datatypes:
data Arrow = Arrow { from :: Point, to :: Point }
data Point = Point { x :: Double, y :: Double }
If you want to shift the arrow, you have to define a function that takes it to parts and repacks it:
shiftArrowX :: Double -> Arrow -> Arrow
shiftArrowX d (Arrow (Point fromX fromY) (Point toX toY)) = Arrow (Point (fromX + d) fromY) (Point (toX + d) toY)
This packing and repacking gets more complicated each time the representation grows. The references library solves this problem by letting you define references:
data Arrow = Arrow { from :: Point, to :: Point }
makeReferences ''Arrow
data Point = Point { x :: Double, y :: Double }
makeReferences ''Point
Then shiftArrowX
can be defined using references:
shiftArrowX :: Double -> Arrow -> Arrow
shiftArrowX d = (from &+& to) & y .- (+d)