Matthew Crews
Matthew Crews

Reputation: 4305

F# Pattern Matching on Generic Parameter

I have a strange one here. I am wanting to match on the type of the generic parameter. Here is what I have so far:

open System.Reflection

type Chicken = {
    Size : decimal
    Name : string
}

let silly<'T> x =
    match type<'T> with
    | typeof<Chicken> -> printfn "%A" x
    | _ -> printfn "Didn't match type"
    enter code here

I am wanting the silly<'T> function to take a generic parameter and to then match on the type in the function to determine the output. Right now I get a compiler error about incorrect indentation. I'm pretty sure the indentation is fine but there is something about what I am doing the compiler simply does not like. Thoughts? I have a brute force workaround but this approach would be much simpler.

Upvotes: 5

Views: 1684

Answers (2)

AMieres
AMieres

Reputation: 5004

I think this is what you are looking for:

let silly x =
    match box x with 
    | :? Chicken as chicken -> printfn "is a  chicken = %s %A" chicken.Name chicken.Size
    | :? string  as txt     -> printfn "is a  string  = '%s'"  txt
    | :? int     as n       -> printfn "is an int     = %d"    n
    | _                     -> printfn "Didn't match type"

Call it like this:

silly "Hello"
silly 7
silly { Name = "Claudius" ; Size = 10m }

// is a  string  = 'Hello'
// is an int     = 7
// is a  chicken = Claudius 10M

Upvotes: 9

GoodGuyJim
GoodGuyJim

Reputation: 251

This is what I've always done, not sure that it's "the best" but it works and makes sense to my team and I.

let silly<'T> x =
  match typeof<'T> with
  | t when t = typeof<TypeA>  -> TypeASpecificFunction x
  | t when t = typeof<TypeB>  -> TypeBSpecificFunction x
  | t when t = typeof<TypeC>  -> TypeCSpecificFunction x
  | _                         -> printfn "Didn't match type"

It requires a generic function which you have, this approach wouldn't work on typeof< x > directly, you have to do typeof<'T>.

Upvotes: 2

Related Questions