DDC/DestructiveUpdate

From HaskellWiki
< DDC
Revision as of 12:09, 16 March 2008 by Benl23 (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Update of base values

Values can be assigned to using the := operator.

 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 for 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