简体   繁体   English

记录与单一案例歧视联盟

[英]Records vs Single-Case Discriminated Unions

What are the Pro's and Con's of using either 什么是Pro和Con使用的

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 在记录类型的情况下,假设您声明了符号it : Complex您可以立即访问这两个字段,如: it.real, it.imag

In the case of discriminated union (DU) you have to first unpack DU type like: 在区分联合(DU)的情况下,您必须首先解压缩DU类型,如:

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

DU makes sense when you have some choices on the type. 当你对类型有一些选择时,DU是有意义的。 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. 在这种情况下,我赞成记录类型,因为它在使用中提供了更易读的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM