Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F#: Nullable<T> Support

Tags:

What is the right way to use Nullable in F#?

Currently I'm using this, but it seems awefully messy.

let test (left : Nullable<int>) = if left.HasValue then left.Value else 0  Console.WriteLine(test (new System.Nullable<int>())) Console.WriteLine(test (new Nullable<int>(100)))  let x = 100 Console.WriteLine(test (new Nullable<int>(x))) 
like image 809
Jonathan Allen Avatar asked Jun 03 '09 19:06

Jonathan Allen


2 Answers

I'm afraid there's no syntactical sugar for nullable types in F# (unlike in C# where you simply append a ? to the type). So yeah, the code you show there does look terribly verbose, but it's the only way to use the System.Nullable<T> type in F#.

However, I suspect what you really want to be using are option types. There's a few decent examples on the MSDN page:

let keepIfPositive (a : int) = if a > 0 then Some(a) else None 

and

open System.IO let openFile filename =    try        let file = File.Open (filename, FileMode.Create)        Some(file)    with        | exc -> eprintf "An exception occurred with message %s" exc.Message; None  

Clearly a lot nicer to use!

Options essentially fulfill the role of nullable types in F#, and I should think you really want to be using them rather than nullable types (unless you're doing interop with C#). The difference in implementation is that option types are formed by a discriminated union of Some(x) and None, whereas Nullable<T> is a normal class in the BCL, with a bit of syntactical sugar in C#.

like image 169
Noldorin Avatar answered Sep 20 '22 13:09

Noldorin


You can let F# infer most of the types there:

let test (left : _ Nullable) = if left.HasValue then left.Value else 0  Console.WriteLine(test (Nullable())) Console.WriteLine(test (Nullable(100)))  let x = 100 Console.WriteLine(test (Nullable(x))) 

You can also use an active pattern to apply pattern matching on nullable types:

let (|Null|Value|) (x: _ Nullable) =     if x.HasValue then Value x.Value else Null  let test = // this does exactly the same as the 'test' function above     function     | Value v -> v     | _ -> 0 

I blogged some time ago about nullable types in F# [/shameless_plug]

like image 39
Mauricio Scheffer Avatar answered Sep 20 '22 13:09

Mauricio Scheffer