I have a couple of domain types in my code that I use to distinguish different types of strings, so the compiler can stop me from e.g. passing arguments in the wrong order:
type Foo = string
type Bar = string
let baz (foo : Foo) (bar : Bar) = printfn "%A %A" foo bar
let f : Foo = "foo"
let b : Bar = "bar"
baz f b // this should be OK
baz b f // this shouldn't compile
However, this currently doesn't work satisfactorily, for two reasons:
null
is not a valid value, so I can't guarantee that a Foo
instance will never be null
.Is there a way to define type aliases that
a) refer to/wrap the same type, but are incompatible with each-other, and
b) disallow null
values, even if the underlying type would allow it?
Aliases can be substituted freely so there's no way to use them for this purpose, but you can use single-case discriminated unions instead. With smart constructors that prevent using null and private implementations (so that code outside of the module where they're defined can't go around the smart constructors), you should basically get what you want (although the checking for null is enforced at runtime rather than compile time, sadly):
type Foo = private Foo of string with
static member OfString(s) =
if s = null then failwith "Can't create null Foo"
else Foo s
type Bar = private Bar of string with
static member OfString(s) =
if s = null then failwith "Can't create null Bar"
else Bar s
let baz (foo : Foo) (bar : Bar) = printfn "%A %A" foo bar
let f = Foo.OfString "foo"
let b = Bar.OfString "bar"
baz f b // ok
baz b f // type error
A variant of @kvb answer is to use an old-timer trick from C++ that relies on "tag" types to create distinguished aliases (C++ typedefs are aliases thus suffer from same benefits and drawbacks as F# type aliases)
Also F#4 don't support struct ADTs (but F#4.1 does) so using ADTs create more objects on heap. My example uses struct types to mitigate heap pressure.
In my own personal preference I consider a null string to be the "same" as the empty string so I think instead of throwing one could treat null as empty.
// NonNullString coalesces null values into empty strings
type NonNullString<'Tag>(s : string) =
struct
member x.AsString = if s <> null then s else ""
override x.ToString () = x.AsString
static member OfString s = NonNullString<'Tag> s
end
// Some tags that will be used when we create the type aliases
type FooTag = FooTag
type BarTag = BarTag
// The type aliases
type Foo = NonNullString<FooTag>
type Bar = NonNullString<BarTag>
// The function
let baz (foo : Foo) (bar : Bar) = printfn "%A, %A" foo.AsString.Length bar.AsString.Length
[<EntryPoint>]
let main argv =
// Some tests
baz (Foo.OfString null) (Bar.OfString "Hello")
// Won't compile
// baz (Bar.OfString null) (Bar.OfString "Hello")
// baz "" (Bar.OfString "Hello")
0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With