string representation of F# function signature

后端 未结 2 1507
-上瘾入骨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:12

    You can analyze types representing F# functions, with the help of the Microsoft.FSharp.Reflection namespace. There is the caveat that generic function arguments default to System.Object, and that other F# types which may form incomplete patterns (e.g. union cases, records) are not included.

    open Microsoft.FSharp.Reflection
    let funString o =
        let rec loop nested t =
            if FSharpType.IsTuple t then
                FSharpType.GetTupleElements t
                |> Array.map (loop true)
                |> String.concat " * "
            elif FSharpType.IsFunction t then
                let fs = if nested then sprintf "(%s -> %s)" else sprintf "%s -> %s"
                let domain, range = FSharpType.GetFunctionElements t
                fs (loop true domain) (loop false range)
            else
                t.FullName
        loop false (o.GetType())
    
    let foo x = x
    funString foo
    // val it : string = "System.Object -> System.Object"
    

提交回复
热议问题