3dGrabber
3dGrabber

Reputation: 5074

Records vs Single-Case Discriminated Unions

What are the Pro's and Con's of using either

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.

Upvotes: 7

Views: 564

Answers (2)

Funk
Funk

Reputation: 11221

Using helper functions you could get the same out of 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

Union 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 imagine the (frequent) decomposition of the union type could influence performance, but I'm no expert on the subject.

Upvotes: 4

Bartek Kobyłecki
Bartek Kobyłecki

Reputation: 2395

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

In the case of discriminated union (DU) you have to first unpack DU type like:

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

DU makes sense when you have some choices on the type. Your Complex type doesn't branch to few cases, it only has one possible shape, case.

In this case I'm in favour of record type as it gives more readable code in usage.

Upvotes: 3

Related Questions