Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 283
Matthew Crews Avatar asked Oct 10 '18 20:10

Matthew Crews


1 Answers

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
like image 146
AMieres Avatar answered Oct 02 '22 01:10

AMieres