Difference between revisions of "DDC/FieldProjections"

From HaskellWiki
< DDC
Jump to navigation Jump to search
 
Line 1: Line 1:
== Data Fields ==
+
== Data fields ==
   
 
When data types are defined using field names, we can use the projection operator <hask>(.)</hask> to select the fields.
 
When data types are defined using field names, we can use the projection operator <hask>(.)</hask> to select the fields.
Line 8: Line 8:
   
 
instance Out Vector where
 
instance Out Vector where
out vec = println $ parens (show x % "," % show y)
+
out vec = println $ parens (show vec.x % "," % show vec.y)
   
 
main ()
 
main ()
Line 16: Line 16:
 
out vec.x -- prints '3.0'
 
out vec.x -- prints '3.0'
 
out vec.y -- prints '4.0'
 
out vec.y -- prints '4.0'
 
 
</haskell>
 
</haskell>
  +
  +
== Custom projections ==

Revision as of 11:24, 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