DEV Community

Discussion on: F# Tip 1: Don't use classes

Collapse
 
rickbradford profile image
RickBradford • Edited

A hybrid way of doing this is to use type extensions. The golden rule is that you keep everything immutable, but streamline the code somewhat.

The example above would be written as :

type Car =
   private 
    {
        Mileage : int
        Color : Color
    }
    static member create color = { Mileage = 0; Color = color }
    member this.drive miles = { this with Mileage = car.Mileage + miles }
    member this.paint color = { this with Color = color }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
shimmer profile image
Brian Berns • Edited

Yes, type classes are definitely a cool way to support "dot" notation in F#. You can even have it both ways by defining a plain record type with a corresponding module of functions, as I did above, and then adding type extensions at the end:

type Car with
   member this.Drive(miles) = this |> Car.drive miles
   member this.Paint(color) = this |> Car.paint color

Usage:

car |> Car.drive 10   // F# style
car.Drive(10)         // C# style

BTW, when I do this, I usually use C# naming conventions for the type extensions: capitalize the first letter and put parens around the arguments, since they can't be curried (e.g. this.Drive(miles) instead of this.drive miles).