Working with Nullable <'T> in F #

I am wondering what others came up with to work with Nullable <T in F #. I want to use Nullable <T> for data types so that serialization works correctly (i.e. Doesn’t write out the option type F # in XML). But I do not want my code stuck in the fight against the ugliness associated with Nullable <T>. Any suggestions?

Is it better to use active templates for a direct match with Nullable, or just for a converter, and use Some / None matching?

In addition, I would really like to hear ideas about eliminating null links in a good manner. If I use, I will say "string parameter", then in the end I get an option like F #, which wraps things. If I do not, I cannot distinguish between truly optional strings and strings that should not be null.

Any chance that .NET 4 will take Option <'T> to help? (If this is part of BCL, then we can see it better ...)

+4
source share
1 answer

Like active templates, since the parameters go well with pattern matching, but it seems like using active templates (i.e. typeof and ?? ) your code will consume more ticks. The main question is how will you deal with your null links? In case your long-chain computation code, it is nice to use the monadic syntax:

 type Maybe<'a> = (unit -> 'a option) let succeed x : Maybe<'a> = fun () -> Some(x) let fail : Maybe<'a> = fun () -> None let run (a: Maybe<'a>) = a() let bind p rest = match run p with None -> fail | Some r -> (rest r) let delay f = fun () -> run (f ()) type MaybeBuilder() = member this.Return(x) = succeed x member this.Let(p,rest) = rest p member this.Bind(p,rest) = bind p rest member this.Delay(f) = delay f let maybe = new MaybeBuilder() let add (a:'a) (b:'a) = maybe { match TryGetNumericAssociation<'a>() with | Some v -> return (v.Add(a,b)) | _ -> return! fail } let add3 (a:'a) (b:'a) (c:'a) = maybe { let! ab = add ab let! abc = add ab c return abc } > let r1 = add 1 2;; val r1 : (unit -> int option) > r1();; val it : int option = Some 3 > let r2 = add "1" "2";; val r2 : (unit -> string option) > r2();; val it : string option = None > let r3 = add3 "one" "two" "three";; val r3 : (unit -> string option) > r3();; val it : string option = None 
+2
source

All Articles