generics - 通用参数上的 F# 模式匹配
问题描述
我这里有一个奇怪的。我想匹配泛型参数的类型。这是我到目前为止所拥有的:
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
推荐阅读
- sql - 获取字符串直到字符 Oracle SQL
- vb.net - 为什么我会收到虚假警告 CA2202?
- c# - 基于组合框填充的简单文本框
- android - 如何通过蓝牙从 raspberry pi 接收 Android 应用程序中的图像并将其在图像视图中显示为 jpg 图像
- xaml - 如何在 XAML 对象上设置附加属性 MyPage.MyParagraph.Text
- angular - 在 ng-if 中使用时正确实现 ng-content 存在
- python - 如何从ordereddict生成多个熊猫数据框?
- android - Android studio : UnsupportedOperationException: Operation is not supported > for read-only collection
- angular - 覆盖离子4中的css变量
- javascript - 如何让相同的 Javascript 自调用函数模式并行运行不止一次而不覆盖值?