Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F#: How do I pattern match a type value?

I have a function that takes a generic parameter, and inside it I need to execute one of two functions depending on the type of the parameter.

member this.Load<'T> _path =
    let hhType = typeof<HooHah>
    match typeof<'T> with
        | hhType -> this.LoadLikeCrazy<'T> _path
        | _ -> this.LoadWithPizzaz<'T> _path

.... where LoadLikeCrazy and LoadWithPizzaz both return a 'T.

VS informs me that the wildcard case will never get executed, since I am apparently getting the type of a generic at compile time, and not the actual type at runtime. How do I go about this?

like image 340
MiloDC Avatar asked Apr 28 '11 03:04

MiloDC


2 Answers

In your code , the first pattern match rule doesn't compare typeof<'T> against hhType. Instead, it will introduce a new value called hhType. That's the reason you got warning. I'd rather modify the code like this.

member this.Load<'T> _path =        
    match typeof<'T> with        
    | x when x = typeof<HooHah>  -> this.LoadLikeCrazy<'T> _path        
    | _ -> this.LoadWithPizzaz<'T> _path
like image 137
Nyi Nyi Avatar answered Sep 21 '22 23:09

Nyi Nyi


Is _path an instance of 'T? If so, Talljoe's solution will work, otherwise you'll have to do something like:

member this.Load<'T> _path =
    if typeof<'T> = typeof<HooHah> then this.LoadLikeCrazy<'T> _path
    else this.LoadWithPizzaz<'T> _path

The reason for the error is that hhType within your match expression is shadowing the prior declaration of hhType. So, it's merely capturing the value of your match expression into a new binding. This matches everything, therefore your wildcard condition will never be hit.

like image 26
Daniel Avatar answered Sep 22 '22 23:09

Daniel