首页 > 解决方案 > 通用参数上的 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>函数采用通用参数,然后匹配函数中的类型以确定输出。现在我收到一个关于不正确缩进的编译器错误。我很确定缩进很好,但是我正在做的事情编译器根本不喜欢。想法?我有一个蛮力解决方法,但这种方法会简单得多。

标签: genericsf#pattern-matching

解决方案


我认为这就是你要找的:

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

推荐阅读