Skip to content

Instantly share code, notes, and snippets.

@artur-s
Created April 19, 2016 05:09
Show Gist options
  • Select an option

  • Save artur-s/7022ee6082118f7facf9e2958dc0f315 to your computer and use it in GitHub Desktop.

Select an option

Save artur-s/7022ee6082118f7facf9e2958dc0f315 to your computer and use it in GitHub Desktop.
A function with constrained return type that implements static TryParse method
// simplified version a snipped found here: http://fssnip.net/sT
let inline tryParse text : ^a option =
let mutable result = Unchecked.defaultof<_>
if (^a : (static member TryParse: string * ^a byref -> bool) (text, &result))
then Some result
else None
// usage
open System
let date : DateTime option = tryParse "10/22/2015 21:47:42"
let nondate : DateTime option = tryParse "nondate"
let text = "12345.6789"
match tryParse text with
| Some v -> printfn "%M" v
| _ -> ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment