Skip to content

References Tutorial

Boldizsár Németh edited this page Sep 30, 2016 · 4 revisions

What is a reference?

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.

Why do we need references?

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)
Clone this wiki locally