8 people like it.

Safely unbox to an option

An extra primitive that can be used to safely unbox to Some. Useful for use with options where only a single type match is needed and a function is only applied if successful.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
[<AutoOpen>]
module ExtraPrimitives =
    let inline tryUnbox<'a> (x:obj) =
        match x with
        | :? 'a as result -> Some (result)
        | _ -> None

let test = box "Hello"

test
|> tryUnbox<string>
|> Option.iter (printfn "%s") 
Multiple items
type AutoOpenAttribute =
  inherit Attribute
  new : unit -> AutoOpenAttribute
  new : path:string -> AutoOpenAttribute
  member Path : string

Full name: Microsoft.FSharp.Core.AutoOpenAttribute

--------------------
new : unit -> AutoOpenAttribute
new : path:string -> AutoOpenAttribute
val tryUnbox : x:obj -> 'a option

Full name: Script.ExtraPrimitives.tryUnbox
val x : obj
type obj = System.Object

Full name: Microsoft.FSharp.Core.obj
val result : 'a
union case Option.Some: Value: 'T -> Option<'T>
union case Option.None: Option<'T>
val test : obj

Full name: Script.test
val box : value:'T -> obj

Full name: Microsoft.FSharp.Core.Operators.box
Multiple items
val string : value:'T -> string

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

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

Full name: Microsoft.FSharp.Core.string
module Option

from Microsoft.FSharp.Core
val iter : action:('T -> unit) -> option:'T option -> unit

Full name: Microsoft.FSharp.Core.Option.iter
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn

More information

Link:http://fssnip.net/ne
Posted:9 years ago
Author:7sharp9
Tags: unbox , cast , primitive , option