Methods in F#

F# supports methods defined on struct types, which are similar to classes in object-oriented programming.

open System

type Rect = { Width: int; Height: int }

// This 'area' method is defined as an extension method on the Rect type
type Rect with
    member this.Area() = 
        this.Width * this.Height

// Methods can also be defined as standalone functions
// Here's an example using a value parameter
let perim (r: Rect) = 
    2 * r.Width + 2 * r.Height

[<EntryPoint>]
let main argv =
    let r = { Width = 10; Height = 5 }

    // Here we call the 2 methods defined for our struct
    printfn "area: %d" (r.Area())
    printfn "perim: %d" (perim r)

    // F# automatically handles method calls on values
    // There's no need for explicit pointer handling as in some other languages
    let rRef = &r
    printfn "area: %d" (rRef.Area())
    printfn "perim: %d" (perim rRef)
    
    0 // return an integer exit code

To run the program:

$ dotnet fsi methods.fsx
area: 50
perim: 30
area: 50
perim: 30

In F#, methods can be defined as extension methods (like Area) or as standalone functions (like perim). The language doesn’t distinguish between value and reference types in the same way as some other languages, so there’s no need for explicit pointer handling.

F# uses a different approach to object-oriented programming compared to some other languages. It favors immutability and functional programming paradigms, but still allows for object-oriented design when needed.

Next, we’ll look at F#’s mechanism for grouping and naming related sets of methods: interfaces.