Skip to content

Instantly share code, notes, and snippets.

@davidgrenier
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidgrenier/9439624 to your computer and use it in GitHub Desktop.
Save davidgrenier/9439624 to your computer and use it in GitHub Desktop.
let inline parse str = (^a: (static member Parse: string -> ^a) (str))
let inline tryParse str =
let mutable value = Unchecked.defaultof<_>
let result = (^a: (static member TryParse: string * byref< ^a > -> bool) (str, &value))
result, value
(tryParse "3": bool * int)
(tryParse "2.3": bool * float)
(tryParse "2.3": bool * decimal)
(tryParse "true": bool * bool)
(tryParse "tRUE": bool * bool)
(parse "2": int)
(parse "test": int)
(parse "2.3": float)
let inline (|Parsed|_|) x =
match tryParse x with
| true, v -> Some v
| _ -> None
match "true" with
| Parsed 3 -> "The int 3"
| Parsed x -> sprintf "An int %i" x
| Parsed (x: float) -> "A float"
| Parsed true -> "True"
| Parsed false -> "False"
| x -> sprintf "Some other string %s" x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment