generics - 通用参数上的 F# 模式匹配

标签 generics f# pattern-matching

我这里有一个奇怪的。我想匹配泛型参数的类型。这是我到目前为止所拥有的:

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/

相关文章:

generics - Java 8 [无法推断类型变量]问题

haskell - 我可以使 -Wincomplete-patterns 更严格吗?

r - 数据帧上下文中的模式匹配

包含选项的 F# 数据类型

f# - F# 中的“和”关键字

asynchronous - 定位 Microsoft.FSharp.Control.Trampoline 抛出的异常

java - JsValue 中的 Scala 模式匹配类型

swift - 如何为不符合特定协议(protocol)的所有类型扩展通用类?

dictionary - 检查 map 是否是另一张 map 的子集

java - Java继承与通用父级的虚拟行为