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

查看:21
本文介绍了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 反射来实现这一点 - 局部变量和函数被定义为单个动态程序集中的静态属性/类型方法.您可以通过调用 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

该函数返回惰性"值(因为这是最简单的编写方法,无需事先读取所有变量的值,这会很慢),因此您需要使用 Value 属性.另请注意,您将返回 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天全站免登陆