7

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#?

6

1 Answer 1

16

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

Sign up to request clarification or add additional context in comments.

6 Comments

The suggestion to use interfaces is great. Thanks!
@Jon: I was expecting that. I just didn't know how and couldn't find any good source of information. Do you have a link to some example (preferably freely available ;-))?
@Tomas: We used phantom types in the Citrix code base to distinguish between different kinds of UUID, catching any errors at compile time. The only difference is that you can use structural types in OCaml to achieve the same effect without having to define any types by hand.
@Tomas: Here is a simple example: camltastic.blogspot.com/2008/05/phantom-types.html
A type-safe SQL query helper module that uses exactly this idea: gist.github.com/yawaramin/552c25a23549f15556d54954e39f946d
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.