DDC/DestructiveUpdate

From HaskellWiki
< DDC
Revision as of 12:17, 16 March 2008 by Benl23 (talk | contribs)
Jump to navigation Jump to search

Update of base values

Values can be assigned to using the := operator, which copies its second argument over its first.

 main ()
  = do   x = 2
         out x   -- prints '2'
 
         x := 3
         out x   -- prints '3'

Update of algebraic data

The structure of algebraic data can be modified with the #= operator. This replaces the constructor at a particular node with a new one.

We'll use a simple point type as an example. In this definition, x and y are field names and are local to the Point type. This is different from Haskell, where all field names are in the top level scope.

 data Point
     = Point { x :: Float; y :: Float; }

We'll also define an instance of the Out type-class, which we're use to print things to stdout until the implementation of dictionary passing for type classes is finished.

 instance Out Point where
     out (Point x y)	= println $ parens (show x % "," % show y)

Values of Point type are constructed in the standard way, and we can use the field names to access their components.

 main ()
  = do   point  = Point 2.0 3.0  -- construct a new point
         out point               -- prints '(2.0, 3.0)' 
	 out point.x             -- prints '2.0'

Accessing the x field gives us a reference to the Float object inside point.

         oldX   = point.x
         out oldX                -- prints '2.0'

When we write a literal value, this creates a whole new object.

         newX = 5

We can now make point reference this new object.

         point#x #= newX
         out point               -- prints '(5.0, 3.0)'
         out oldX                -- oldX is still '2.0'

Implicit References

In Disciple, we don't need to change our data definitions to include Ref or IORef types in order to update them. References are created on the fly with the reference projection operator # which we used in the previous example.

In the example, when we used # we got.

        (point # x) :: Ref Float

Which holds a pointer into the point object.

The #= operator is just a regular function which has the (simplified) type:

        (#=) :: forall a. Ref a -> a -> ()