string representation of F# function signature

后端 未结 2 1494
-上瘾入骨i
-上瘾入骨i 2021-01-11 20:27

When I\'m working in the F# REPL fsharpi whenever I enter a new function the signature is printed after I\'ve entered them:

> let foo x = x;;         


        
2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-11 21:26

    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 () = typeofint>.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"
        | typ when typ = typeof -> "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 (typeofint>.GetGenericTypeDefinition())
    // val it: string = "'T -> 'TResult"
    

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

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

提交回复
热议问题