f-sharp
  1. f-sharp-data-types

F# Data Types

Syntax

type TypeName =
    | UnionCase1 of Type1 * Type2
    | UnionCase2 of Type3
    member this.MethodName(arg1: Type4): Type5 =
        // Method body

Example

type Shape =
    | Circle of float
    | Rectangle of float * float

let area (s: Shape) =
    match s with
    | Circle(r) -> Math.PI * r * r
    | Rectangle(w, h) -> w * h

let circle = Circle(5.0)
let rectangle = Rectangle(5.0, 10.0)

let circleArea = area circle
let rectangleArea = area rectangle

Output

78.53981633974483
50.0

Explanation

F# supports various data types, including records, tuples, enums, and discriminated unions. The type keyword is used to define a new data type.

The Shape type in the example above is a discriminated union type, which means it can have multiple cases. Each case can have its own data types. In this case, the Circle case has a single float parameter, while the Rectangle case has two float parameters.

The area function takes a Shape parameter and uses pattern matching to calculate the area of the shape. If the shape is a Circle, it calculates the area using the formula πr^2, where r is the radius. If the shape is a Rectangle, it calculates the area using the formula w * h, where w is the width and h is the height.

The code then creates instances of the Shape type using the Circle and Rectangle cases, and calculates their respective areas.

Use

Data types in F# are used to define the structure of the data in a program. They help ensure type safety and make the code easier to read and maintain.

For example, a program that deals with geometric shapes would benefit from defining a Shape type as a discriminated union with various cases representing different shapes.

Important Points

  • F# supports various data types, including records, tuples, enums, and discriminated unions.
  • The type keyword is used to define a new data type.
  • Discriminated unions are a type of data type in F# that can have multiple cases, each with its own data types.
  • Pattern matching is a powerful language construct in F# that is often used with discriminated unions.

Summary

Data types are a fundamental concept in programming, and F# offers a flexible and powerful system for defining types. Discriminated unions are a particularly useful data type in F# that allow for the creation of complex data structures with ease. Understanding and effectively using data types is key to writing robust and maintainable F# code.

Published on: