- F# - Namespaces
- F# - Modules
- F# - Events
- F# - Interfaces
- F# - Inheritance
- F# - Operator Overloading
- F# - Structures
- F# - Classes
- F# - Exception Handling
- F# - Pattern Matching
- F# - Enumerations
- F# - Delegates
- F# - Generics
- F# - Basic I/O
- F# - Mutable Dictionary
- F# - Mutable Lists
- F# - Arrays
- F# - Mutable Data
- F# - Discriminated Unions
- F# - Maps
- F# - Sets
- F# - Sequences
- F# - Lists
- F# - Records
- F# - Tuples
- F# - Options
- F# - Strings
- F# - Functions
- F# - Loops
- F# - Decision Making
- F# - Operators
- F# - Variables
- F# - Data Types
- F# - Basic Syntax
- F# - Program Structure
- F# - Environment Setup
- F# - Overview
- F# - Home
F# Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
F# - Structures
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: 5Advertisements