3 people like it.

Null Value guard active pattern

An active pattern that protects from null reference exceptions stemming from pattern matches on values materialized by .NET libraries such as Newtonsoft.Json

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
let (|Null|NotNull|) (x : 'T when 'T : not struct) =
    if obj.ReferenceEquals(x, null) then Null else NotNull x

// Examples

// throws nullreference exception
match [Unchecked.defaultof<int ref>] with
| [{ contents = 42 }] -> true
| _ -> false

// evaluates to 1
match [Unchecked.defaultof<int ref>] with
| [NotNull { contents = 42 }] -> 0
| [Null] -> 1
val x : 'T (requires reference type)
val not : value:bool -> bool

Full name: Microsoft.FSharp.Core.Operators.not
type obj = System.Object

Full name: Microsoft.FSharp.Core.obj
System.Object.ReferenceEquals(objA: obj, objB: obj) : bool
module Unchecked

from Microsoft.FSharp.Core.Operators
val defaultof<'T> : 'T

Full name: Microsoft.FSharp.Core.Operators.Unchecked.defaultof
Multiple items
val int : value:'T -> int (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.int

--------------------
type int = int32

Full name: Microsoft.FSharp.Core.int

--------------------
type int<'Measure> = int

Full name: Microsoft.FSharp.Core.int<_>
Multiple items
val ref : value:'T -> 'T ref

Full name: Microsoft.FSharp.Core.Operators.ref

--------------------
type 'T ref = Ref<'T>

Full name: Microsoft.FSharp.Core.ref<_>
active recognizer NotNull: 'T -> Choice<unit,'T>

Full name: Script.( |Null|NotNull| )
active recognizer Null: 'T -> Choice<unit,'T>

Full name: Script.( |Null|NotNull| )
Raw view Test code New version

More information

Link:http://fssnip.net/7UQ
Posted:6 years ago
Author:Eirik Tsarpalis
Tags: #active patterns