开发者

Implementing phantom types in F#

开发者 https://www.devze.com 2023-01-13 15:47 出处:网络
Ocaml programmers can use so called \'phantom types\' to enforce some constraints using the type system. A nice example can be found at开发者_JS百科 http://ocaml.janestreet.com/?q=node/11.

Ocaml programmers can use so called 'phantom types' to enforce some constraints using the type system. A nice example can be found at开发者_JS百科 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#?


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消