English 中文(简体)
F# - Structures
  • 时间:2024-09-08

F# - Structures


Previous Page Next Page  

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 [accessibipty-modifier] type-name =
   struct
      type-definition-elements
   end
// or
[ attributes ]
[<StructAttribute>]
type [accessibipty-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.

Unpke 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 initiapze the field value, instead they are initiapzed to zero or null. So for a structure having an imppcit constructor, the val declarations be annotated with the DefaultValue attribute.

Example

The following program creates a pne structure along with a constructor. The program calculates the length of a pne 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