且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

F#函数签名的字符串表示形式

更新时间:2023-11-02 22:39:28

AFAIK,FSharp.Core中没有用于获取类型字符串表示形式的函数,就像在编译器中看到的一样(尽管FSharp.Compiler.Services中可能有某些功能) -我没有检查).这是一个适用于大多数简单用途的小功能:

AFAIK, there's no function in FSharp.Core for getting a type's string representation as it would appear to the compiler (though maybe there's something in FSharp.Compiler.Services -- I haven't checked). Here's a small function that works for most simple uses:

open System

let (|TFunc|_|) (typ: Type) =
    if typ.IsGenericType && typ.GetGenericTypeDefinition () = typeof<int->int>.GetGenericTypeDefinition () then
        match typ.GetGenericArguments() with
        | [|targ1; targ2|] -> Some (targ1, targ2)
        | _ -> None
    else
        None

let rec typeStr (typ: Type) =
    match typ with
    | TFunc (TFunc(_, _) as tfunc, t) -> sprintf "(%s) -> %s" (typeStr tfunc) (typeStr t)
    | TFunc (t1, t2) -> sprintf "%s -> %s" (typeStr t1) (typeStr t2)
    | typ when typ = typeof<int> -> "int"
    | typ when typ = typeof<string> -> "string"
    | typ when typ.IsGenericParameter -> sprintf "'%s" (string typ)
    | typ -> string typ


typeStr typeof<(string -> (string -> int) -> int) -> int>
// val it: string = "string -> (string -> int) -> int"
typeStr (typeof<int->int>.GetGenericTypeDefinition())
// val it: string = "'T -> 'TResult"

您可以在此之上轻松编写一个函数,以在值的类型上使用typeStr:

You can easily write a function on top of this to use typeStr on a value's type:

let valTypeString x = typStr (x.GetType ())