Records Against Single Disc Discrimination Unions

What is Pro and Con when using

type Complex = 
    { 
        real: float; 
        imag: float;
    }

or

type Complex = 
    Complex of 
        real: float * 
        imag: float

I am particularly interested in readability and handling in different situations.
And, to a lesser extent, performance.

+4
source share
2 answers

Using helper functions, you can get the same thing from both approaches.

Record

type ComplexRec = 
    { 
        real: float 
        imag: float
    }

// Conciseness
let buildRec(r,i) =
    { real = r ; imag = i }

let c = buildRec(1.,5.)

// Built-in field acces
c.imag

Connection type

type ComplexUnion = 
    Complex of 
        real: float * imag: float

// Built-in conciseness
let c = Complex(1.,5.)

// Get field - Could be implemented as members for a more OO feel
let getImag = function
    Complex(_,i) -> i

getImag c

I suggest that (frequent) decomposition of a union type can affect performance, but I'm not an expert on this.

+4
source

In the case of a record type, let's say you declared a symbol it : Complex, you have immediate access to both fields:it.real, it.imag

(DU) DU-, :

match it with
| Complex (real, imag) -> real, imag

DU , . , , .

, .

+3

Source: https://habr.com/ru/post/1674186/


All Articles