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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With