f# – 记录与单一案例歧视联盟

前端之家收集整理的这篇文章主要介绍了f# – 记录与单一案例歧视联盟前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
什么是Pro和Con使用的

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

要么

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

我对不同情况下的可读性和处理特别感兴趣.
并且在较小程度上,表现.

解决方法

使用辅助函数可以从两种方法中获得相同的结果.

记录

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

联盟类型

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

我想联盟类型的(频繁)分解会影响性能,但我不是这方面的专家.

猜你在找的设计模式相关文章