Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

types - Variants or Polymorphic variants?

I noticed that, among OCaml programmers I know, some of them always use polymorphic variants (variants that are not declared, prefixed with a backquote), while other ones never use polymorphic variants, and prefer variants declared in types.

Except for performance reasons (polymorphic variants are currently compiled less efficiently than simple variants), how do expert OCaml developers choose between them ?

question from:https://stackoverflow.com/questions/9367181/variants-or-polymorphic-variants

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My usage can be divided into the following 5 categories. 1. interface 2. modularity 3. legibility 4. brevity 5. tricks

  1. If the variant type is only internal to the module, I use regular variants, because as you said they are compiled more efficiently.
  2. If the variant type is exported in the interface and I feel that some cases could appear in other modules but it wouldn't necessarily make sense to make them dependend on the module, I use polymorphic variants because they are not tied to the module namespace system. Examples: the encoding type type of Xmlm. Also having the signal type as a variant type means you can develop modules using the same idea for XML processing without introducing a dependency on Xmlm.
  3. If the variant type is exported in the interface I find it sometimes too verbose to use regular variants when values of the variant type are given to functions of the module. Example: the version type of Uuidm. Instead of having to write Uuidm.create Uuidm.V4 you can simply write Uuidm.create `V4, which is as clear and less verbose.
  4. Sometimes a particular function may return different cases. If these cases are only used by this function I declare the function type in the interface without having to introduce a type definition. For example parse : string -> [`Error of string | `Ok of t]
  5. Polymorphic variants and their subtyping allow you enforce invariants statically with phantom types. Besides the possibility of defining them incrementally can be useful, both for enforcing invariants statically and for documentation purposes.

Finally I sometimes use polymorphic variants in the implementation of a module according to 4. but without them showing up in the interface. I discourage this usage unless you declare the polymorphic variants and close them because it weakens the static typing discipline.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...