我这里有一个奇怪的。我想匹配泛型参数的类型。这是我到目前为止所拥有的:
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
我想要
silly<'T>
函数采用泛型参数,然后匹配函数中的类型以确定输出。现在我收到一个关于不正确缩进的编译器错误。我很确定缩进没问题,但是编译器根本不喜欢我正在做的事情。想法?我有一个蛮力解决方法,但这种方法会简单得多。
最佳答案
我认为这就是你要找的:
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"
像这样调用它:
silly "Hello"
silly 7
silly { Name = "Claudius" ; Size = 10m }
// is a string = 'Hello'
// is an int = 7
// is a chicken = Claudius 10M
关于generics - 通用参数上的 F# 模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52748117/