4 people like it.

One tryParse to rule them all

target type statically type constrained tryParse function over all .Net types implementing static TryParse functions.

1: 
2: 
3: 
4: 
5: 
6: 
7: 
8: 
9: 
  let inline tryParse 
    defaultVal 
    text 
    : ^a when ^a : (static member TryParse : string * ^a byref -> bool) 
    = 
    let r = ref defaultVal
    if (^a : (static member TryParse: string * ^a byref -> bool) (text, &r.contents)) 
    then !r 
    else defaultVal
val tryParse : defaultVal:'a -> text:string -> 'a (requires member TryParse)

Full name: Script.tryParse
val defaultVal : 'a (requires member TryParse)
val text : string
Multiple items
val string : value:'T -> string

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

--------------------
type string = System.String

Full name: Microsoft.FSharp.Core.string
type byref<'T> = (# "<Common IL Type Omitted>" #)

Full name: Microsoft.FSharp.Core.byref<_>
type bool = System.Boolean

Full name: Microsoft.FSharp.Core.bool
val r : 'a ref (requires member TryParse)
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<_>
Ref.contents: 'a
Raw view Test code New version

More information

Link:http://fssnip.net/sT
Posted:8 years ago
Author:George Dennie
Tags: tryparse