F#函数签名的字符串表示形式 [英] string representation of F# function signature

查看:74
本文介绍了F#函数签名的字符串表示形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在F#REPL fsharpi中工作时,每当我输入新功能时,输入它们后便会打印出签名:

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;;
val foo : x:'a -> 'a

有没有办法将其检索为字符串?我问的原因是我正在使用IfSharp而不显示签名的Jupyter笔记本,但是我希望能够显示功能类型以供演示.

Is there a way to retrieve this as a string? The reason I'm asking is that I'm using IfSharp for Jupyter notebooks which doesn't display the signatures, but I'd like to be able to show the types of functions for demonstration purposes.

我已经弄乱了一点,但是找不到任何有用的东西,我已经尝试过了:

I've messed around a bit but can't get anything useful, I've tried:

let foo x = (x, x)
printfn "%A" (foo.GetType())
printfn "%A" foo

但这不是我所需要的:

FSI_0013+clo@3-1
<fun:it@5-2>

是否可以完全访问此内容?

Is it possible to access this at all?

推荐答案

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 ())

这篇关于F#函数签名的字符串表示形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆