Structs

Category:
Defining Types
Description: Structs are lightweight data structures, stored on the Stack. They use value equality comparison.
Code:
[<Struct>]
type StructBox (width: float, height: float, depth: float) =
member box.Width = width
member box.Height = height
member box.Depth = depth

type StructVector2D (dx: float, dy: float) =
struct
member v.DX = dx
member v.DY = dy
member v.Length = sqrt (v.DX * v.DX + v.DY * v.DY)
end

let structSample() =
// a simple struct - must use [] attribute tag or 'struct' 'end' keywords to define as struct
// []
// type StructBox (width: float, height: float, depth: float) =
// member box.Width = width
// member box.Height = height
// member box.Depth = depth

// type StructVector2D (dx: float, dy: float) =
// struct
// member v.DX = dx
// member v.DY = dy
// member v.Length = sqrt (v.DX * v.DX + v.DY * v.DY)
// end

let b1 = StructBox(2.0, 3.0, 6.0)
let v1 = StructVector2D(3.0, 4.0)
let v2 = StructVector2D(3.0, 4.0)

printfn "b1.Width = %A" b1.Width
printfn"\nv1.Length = %A" v1.Length
printfn"\nv1 = v2?\t%A" (v1=v2)

Execution Result:
b1.Width = 2.0

v1.Length = 5.0

v1 = v2? true

Last edited Sep 14, 2011 at 2:37 AM by ttliu2000, version 2

Comments

No comments yet.