My Technical Notes

Monday, 11 August 2014

F#: Pattern matching on the Type of Input

Pattern matching based on the type of the input is readily done easily using a syntax called "Active Patterns". First we define our active pattern As:


let (|As|_|) (p:'T) : 'U option =
    let p = p :> obj
    if p :? 'U then Some (p :?> 'U) else None

Thereafter, to use it is results in very natural code:


let handleType x = 
    match x with
    | As (x:int) -> printfn "is integer: %d" x
    | As (s:string) -> printfn "is string: %s" s
    | _ -> printfn "Is neither integer nor string"

Here is some code to test the above code:


// test 'handleType'
handleType 1
handleType "tahir"
handleType 2.
let stringAsObj = "tahir" :> obj
handleType stringAsObj

I first posted this solution on StackOverflow.com.

No comments: