You can do

type X = X of int

e.g. a single-case DU, and get many of the benefits. However it comes at the cost of an extra allocation/indirection. We will consider adding an attribute so that you can decorate this to say "just erase 'X', make it a compile-time typechecking thing only, with no runtime representation", but this is unlikely to make the cut for the first supported release of F# in VS2010.

Another possibility people sometimes use in .Net is to wrap a struct around your data - a struct with a single member can have zero run-time overhead and add the type safety you want. I never do this because I hate structs. I do use the 'single case DU' idiom a bit, but beware the runtime cost.

By on 3/19/2009 11:30 AM ()

You could use a union:

> type Int1 = Int1 of int
- type Int2 = Int2 of int
- ;;

type Int1 = | Int1 of int
type Int2 = | Int2 of int

> let x = Int1 5;;
val x : Int1

> let y = Int2 5;;
val y : Int2

> let foo (x : Int1) = printfn "%A" x;;
val foo : Int1 -> unit

> foo x;;
Int1 5
val it : unit = ()

> foo y;;
foo y;;
----^^
stdin(30,5): error FS0001: This expression has type
Int2
but is here used with type
Int1.

By on 3/19/2009 11:27 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper