单一案件歧视工会的目的 [英] Purpose of a single case discriminated union
问题描述
我正在定义一个Monadic可观察/反应解析器.这与普通解析器的行为完全不同,因为它是连续查询.底层类型是:
I'm defining a monadic observable/reactive parser. This behaves quite differently to a normal parser as it is a continuous query. The underlying type is:
IObservable<'a> -> IObservable<'b>
通过查看功能语言中的各种解析器实现,看来定义事物的更合适方法是使用区分大小写的单一联合:
From looking at various parser implementations in functional languages, it seems as though the more appropriate way to define things is a single case discriminated union:
type Pattern<'a,'b> = Pattern of (IObservable<'a> -> IObservable<'b>)
这意味着我需要提取基础函数才能使用它:
Which means I then need to extract the underlying function to use it:
let find (Pattern p) = p
问题是:这仅仅是出于约定,还是出于以后扩展的目的,或者即使定义永远不变,也有这样做的理由吗?
The question is: Is this just by convention, or for purposes of later extension, or is there a reason to do this even if the definition never changes?
奖金问题:如果只是为了使用更方便的类型签名,为什么不只使用类型别名:
Bonus question: If it's just for a more convenient type signature, why not just use a type alias:
type Pattern<'a,'b> = IObservable<'a> -> IObservable<'b>
我已经通过了相当多的改进,但是还没有发现不使用DU会影响可组合性的情况.
I've advanced quite a way through this, and haven't found a case where composability is affected by not using the DU.
推荐答案
F#编译器不会保留有关类型缩写的信息,因此您根本不会从类型推断中受益.类型签名可以理解为程序规范.让类型检查器执行工作是确保程序正确性的好方法.
F# compiler doesn't preserve information about type abbreviation, so you do not benefit from type inference at all. Type signature can be understood as program specification; letting the type checker do their job is a good way to ensure correctness of your programs.
在类型别名的情况下,您需要在所有位置显式指定类型注释:
You need explicitly specify type annotation everywhere in the case of type alias:
type Vector = float * float
// val add : float * float -> float * float -> Vector
let add ((x1, y1): Vector) ((x2, y2): Vector): Vector = (x1 + y1, x2 + y2)
但它不会像使用DU那样为您提供透明度:
but it doesn't give you transparency as using DUs:
type Vector = V of float * float
// val add : Vector -> Vector -> Vector
let add (V(x1, y1)) (V(x2, y2)) = V(x1 + y1, x2 + y2)
在复杂的程序中,明确的类型签名确实使维护可组合性更加容易.
In complex programs clear type signatures indeed make it easier to maintain composability.
将更多案例添加到单案例DU不仅更简单,而且使用成员方法和静态方法扩展DU更加容易.一个示例是您经常覆盖ToString()
进行漂亮的打印.
Not only it's simpler to add more cases to single-case DUs, but also it's easier to extend DUs with member and static methods. One example is you often override ToString()
for pretty printing.
这篇关于单一案件歧视工会的目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!