F#交互式-如何查看当前会话中定义的所有变量 [英] F# interactive - how to see all the variables defined in current session

查看:65
本文介绍了F#交互式-如何查看当前会话中定义的所有变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在F#交互式中,如何查看此会话中定义的变量/函数列表?就像python中的函数whos()或R中的ls()一样?谢谢.

In F# interactive, how can I see a list of variables/functions defined in this session? Like a function whos() in python or ls() in R? Thanks.

推荐答案

您可能可以使用.NET Reflection实现此目的-局部变量和函数被定义为单个动态程序集中的静态属性/类型的方法.您可以通过调用GetExecutingAssembly(在FSI本身中),然后浏览类型以找到所有合适的属性来获取该程序集.

You can probably implement this using .NET Reflection - local variables and functions are defined as static properties/methods of types in a single dynamic assembly. You can get that assembly by calling GetExecutingAssembly (in FSI itself) and then browse the types to find all suitable properties.

以下是用于获取局部变量的合理工作功能:

The following is a reasonably working function for getting local variables:

open System.Reflection
open System.Collections.Generic

let getVariables() = 
  let types = Assembly.GetExecutingAssembly().GetTypes()
  [ for t in types |> Seq.sortBy (fun t -> t.Name) do
      if t.Name.StartsWith("FSI_") then 
        let flags = BindingFlags.Static ||| BindingFlags.NonPublic |||
                    BindingFlags.Public
        for m in t.GetProperties(flags) do 
          yield m.Name, lazy m.GetValue(null, [||]) ] |> dict

这里是一个例子:

> let test1 = "Hello world";;
val test1 : string = "Hello world"

> let test2 = 42;;
val test2 : int = 42

> let vars = getVariables();;
val vars : System.Collections.Generic.IDictionary<string,Lazy<obj>>

> vars.["test1"].Value;;
val it : obj = "Hello world"

> vars.["test2"].Value;;
val it : obj = 42

该函数返回惰性"值(因为这是最简单的写方法,无需事先读取所有 all 变量的值,这会很慢),因此您需要使用属性.另请注意,您会返回object-因为F#类型系统无法识别类型-您必须动态使用它.您可以通过遍历vars ...

The function returns "lazy" value back (because this was the simplest way to write it without reading values of all variables in advance which would be slow), so you need to use the Value property. Also note that you get object back - because there is no way the F# type system could know the type - you'll have to use it dynamically. You can get all names just by iterating over vars...

这篇关于F#交互式-如何查看当前会话中定义的所有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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