3dG*_*ber 5 f# record discriminated-union
使用这两种方式的优点和缺点是什么
type Complex =
{
real: float;
imag: float;
}
Run Code Online (Sandbox Code Playgroud)
要么
type Complex =
Complex of
real: float *
imag: float
Run Code Online (Sandbox Code Playgroud)
我对不同情况下的可读性和处理特别感兴趣。
并在较小程度上提高了性能。
使用辅助函数,您可以从这两种方法中得到相同的结果。
记录
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
Run Code Online (Sandbox Code Playgroud)
联合型
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
Run Code Online (Sandbox Code Playgroud)
我想联合类型的(频繁)分解可能会影响性能,但我不是这个主题的专家。