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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With