F# - Structures


Advertisements

A structure in F# is a value type data type. It helps you to make a single variable, hold related data of various data types. The struct keyword is used for creating a structure.

Syntax

Syntax for defining a structure is as follows −

[ attributes ]
type [accessibility-modifier] type-name =
   struct
      type-definition-elements
   end
// or
[ attributes ]
[<StructAttribute>]
type [accessibility-modifier] type-name =
   type-definition-elements

There are two syntaxes. The first syntax is mostly used, because, if you use the struct and end keywords, you can omit the StructAttribute attribute.

The structure definition elements provide −

  • Member declarations and definitions.
  • Constructors and mutable and immutable fields.
  • Members and interface implementations.

Unlike classes, structures cannot be inherited and cannot contain let or do bindings. Since, structures do not have let bindings; you must declare fields in structures by using the val keyword.

When you define a field and its type using val keyword, you cannot initialize the field value, instead they are initialized to zero or null. So for a structure having an implicit constructor, the val declarations be annotated with the DefaultValue attribute.

Example

The following program creates a line structure along with a constructor. The program calculates the length of a line using the structure −

type Line = struct
   val X1 : float
   val Y1 : float
   val X2 : float
   val Y2 : float

   new (x1, y1, x2, y2) =
      {X1 = x1; Y1 = y1; X2 = x2; Y2 = y2;}
end
let calcLength(a : Line)=
   let sqr a = a * a
   sqrt(sqr(a.X1 - a.X2) + sqr(a.Y1 - a.Y2) )

let aLine = new Line(1.0, 1.0, 4.0, 5.0)
let length = calcLength aLine
printfn "Length of the Line: %g " length

When you compile and execute the program, it yields the following output −

Length of the Line: 5
Advertisements