Implementing phantom types in F#

二次信任 提交于 2019-12-17 16:22:44

问题


Ocaml programmers can use so called 'phantom types' to enforce some constraints using the type system. A nice example can be found at http://ocaml.janestreet.com/?q=node/11.

The syntax type readonly doesn't work in F#. It could be replaced with a pseudo-phantom type defined as type readonly = ReadOnlyDummyValue in order to implement the tricks in the above mentioned blog post.

Is there a better way to define phantom types in F#?


回答1:


I think that defining type just using type somename won't work in F#. The F# compiler needs to generate some .NET type from the declaration and F# specification doesn't explicitly define what should happen for phantom types.

You can create a concrete type (e.g. with type somename = ReadOnlyDummyValue) in the implementation file (.fs) and hide the internals of the type by adding just type somename to the interface file (.fsi). This way you get quite close to a phantom type - the user outside of the file will not see internals of the type.

Another appealing alternative would be to use interfaces. This sounds logical to me, because empty interface is probably the simplest type you can declare (and it doesn't introduce any dummy identifiers). Empty interface looks like this:

type CanRead = interface end
type CanWrite = interface end

The interesting thing, in this case, is that you can also create inherited interfaces:

type CanReadWrite = 
  inherit CanRead
  inherit CanWrite

Then you can write a function that can take values of type Ref<CanRead, int> but also values of type Ref<CanReadWrite, int> (because these values also support reading):

let foo (arg:Ref<#CanRead, int>) = // ...    

This seems like something that could be useful. I would be actually quite interested whether this can be done in OCaml too (because it relies on the F# support for interfaces and inheritance).



来源:https://stackoverflow.com/questions/3583679/implementing-phantom-types-in-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!