Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match Nullable Date parameter in f#

Tags:

nullable

f#

Learning F#, can't find the answer to this... I'd like to handle case where a Nullable parameter (DateTime? in the original c#) is null, but I get the error "Nullable does not have null as a proper value". What is the correct way to do this?

let addIfNotNull(ht:Hashtable, key:string, value:Nullable<DateTime>) = 
        match value with 
        | null -> ()
        | _ -> ht.Add(key,value)
        ht  
like image 692
LineloDude Avatar asked Mar 19 '19 21:03

LineloDude


2 Answers

From https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/symbol-and-operator-reference/nullable-operators:

The actual value can be obtained from a System.Nullable<'T> object by using the Value property, and you can determine if a System.Nullable<'T> object has a value by calling the HasValue method.

So instead of the match you do

if value.HasValue then ht.Add(key, value.Value)

You could use

match Option.ofNullable value with ...

or declare some active patterns to help.

like image 66
Alexey Romanov Avatar answered Sep 30 '22 21:09

Alexey Romanov


While @AlexeyRomanov's answer is perfectly valid, if you really want to match over a Nullable value, you can define an Active Pattern like so:

let (|Null|Value|) (x : _ Nullable) =
    if x.HasValue then Value x.Value else Null

And then use it in your function:

let addIfNotNull (ht : Hashtable) (key : string)
                 (value : Nullable<DateTime>) =
    match value with
    | Null -> ()
    | Value dt -> ht.Add (key, dt)
    ht

I took the liberty to change your function's signature so it takes curried parameters; unless you have specific requirements, curried parameters are usually preferred over tupled parameters.

like image 25
dumetrulo Avatar answered Sep 30 '22 21:09

dumetrulo