This project is read-only.
Records with Members

Category:
Defining Types
Description: F# allows values to be associated with type names, i.e. the type name can be used as a container for 'members' of that type. These are treated the same way as .NET object model members.
Code:
type PointWithMembers = 
{ x: float; y: float}
member p.VectorFromOrigin = { dx = p.x; dy = p.y }
static member Origin = { x = 0.0; y = 0.0 }
static member (+) ((p:PointWithMembers),(v:VectorWithMembers)) =
{ x = p.x + v.dx; y = p.y + v.dy }

and VectorWithMembers =
{ dx: float; dy: float}
static member Zero = { dx = 0.0; dy = 0.0 }
static member OneX = { dx = 1.0; dy = 0.0 }
static member OneY = { dx = 0.0; dy = 1.0 }
static member (+) ((v1:VectorWithMembers),(v2:VectorWithMembers)) =
{ dx = v1.dx + v2.dx; dy = v1.dy + v2.dy }

let MemberSample1() =
printfn "Point.Origin = \n%A" PointWithMembers.Origin;
printfn "Point.Origin + Vector.OneX = \n%A" (PointWithMembers.Origin + VectorWithMembers.OneX);
printfn "Vector.OneX + Vector.OneY = \n%A" (VectorWithMembers.OneX + VectorWithMembers.OneY)

Execution Result:
Point.Origin = 
{x = 0.0;
y = 0.0;}
Point.Origin + Vector.OneX =
{x = 1.0;
y = 0.0;}
Vector.OneX + Vector.OneY =
{dx = 1.0;
dy = 1.0;}

Last edited Sep 14, 2011 at 3:59 AM by ttliu2000, version 1

Comments

No comments yet.