DDC/FieldProjections: Difference between revisions

From HaskellWiki
< DDC
No edit summary
No edit summary
Line 19: Line 19:


== Custom projections ==
== Custom projections ==
We can also define our own projections.
<haskell>
project Vector where
        magnitude (Vector x y)
        = sqrt (x * x + y * y)
</haskell>

Revision as of 11:26, 18 March 2008

Data fields

When data types are defined using field names, we can use the projection operator (.) to select the fields.

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

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

main ()
 = do   vec = Vector 3.0 4.0
        out vec        -- prints '(3.0, 4.0)'

        out vec.x      -- prints '3.0'
        out vec.y      -- prints '4.0'

Custom projections

We can also define our own projections.

project Vector where
        magnitude (Vector x y)
         = sqrt (x * x + y * y)