Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullablle<>'s and "null" in F#

Tags:

f#

I'm calling functions in the XNA framework from F# that accept Nullable values. Now, in C#, you would just call:

foo(arg1, arg2, null, arg4)

Now, I tried that in F#, but it doesn't like it. It says: "Error 9 Type constraint mismatch. The type 'a is not compatible with type System.Nullable The type 'System.Nullable' does not have 'null' as a proper value."

I understand why this is happening, sort of, but it seems really inconvenient. All I'm doing now is, to make life easier, instead of repeatedly typing (Nullable<Rectangle>)null everytime I call the function, I just did let nullRect = (Nullable<Rectangle>)null, and use nullRect. This seems really stupid, especially since I'd have to do that for every nullable type I interact with. Is there a better, more idiomatic way to handle this?

like image 293
Perrako Avatar asked Sep 02 '10 13:09

Perrako


1 Answers

Here's what I'd do:

[<GeneralizableValue>]
let nl<'a when 'a : struct
           and 'a : (new : unit -> 'a)
           and 'a :> System.ValueType> : System.Nullable<'a> =
  unbox null

Now you can use nl wherever you would have used null before.

EDIT

As Tomas notes, this can be written much more concisely as:

let nl = System.Nullable<_>()
like image 53
kvb Avatar answered Sep 23 '22 02:09

kvb