F# 相当于 Eval

发布于 2024-08-28 10:37:44 字数 213 浏览 3 评论 0原文

F# 是否有与 eval 等效的函数?我的目的是让我的应用程序从文件中加载一个小代码示例,本质上

let file = "c:\mysample"
let sample = loadFromFile file
let results = eval(sample)

我是 F# 新手,并在将其应用到项目之前尝试找出一些限制。

谢谢

Is there an F# equivalent to eval? My intent is to have my app load a small code sample from a file and essentially

let file = "c:\mysample"
let sample = loadFromFile file
let results = eval(sample)

I am new to F# and trying to figure out some of the limitations before I apply it to a project.

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眼泪也成诗 2024-09-04 10:37:44

没有任何函数可以让您直接执行此操作。但是,当您想要以编程方式编译 F# 源文件时,可以从应用程序调用 F# 编译器。最简单的方法是使用 F# CodeDOM 提供程序,它作为 F# PowerPack 的一部分提供(在 FSharp.Compiler.CodeDom.dll 程序集中)。但请注意,您需要在用户计算机上安装 F# 编译器。

运行编译器的代码大致如下所示:

open Microsoft.FSharp.Compiler.CodeDom

let provider = new FSharpCodeProvider()
let compiler = provider.CreateCompiler()

let parameters = new CompilerParameters
  (GenerateExecutable = true, OutputAssembly = "file.exe")
let results = icc.CompileAssemblyFromFile(parameters, "filename.fs")

将源文件编译成程序集后,您需要使用 .NET Reflection 加载程序集并从程序集中运行某些特定函数或类(例如,您可以查看对于具有某些特殊名称或标记有某些属性的函数)。

(作为旁注,使用引号或编写自己的解释器,如 相关的 SO 问题 可能是一个选择,但如果您想支持 F# 的全部功能,则可能不是一个选择)

There is no function that would allow you to do this directly. However, when you want to compile an F# source file programatically, you can invoke the F# compiler from your application. The easiest way to do this is to use F# CodeDOM provider, which is available as part of the F# PowerPack (in the FSharp.Compiler.CodeDom.dll assembly). However, note that you need to have the F# compiler installed on the user's machine.

The code to run the compiler would look roughly like this:

open Microsoft.FSharp.Compiler.CodeDom

let provider = new FSharpCodeProvider()
let compiler = provider.CreateCompiler()

let parameters = new CompilerParameters
  (GenerateExecutable = true, OutputAssembly = "file.exe")
let results = icc.CompileAssemblyFromFile(parameters, "filename.fs")

Once you compile the source file into an assembly, you'll need to load the assembly using .NET Reflection and run some specific function or class from the assembly (you can for example look for a function with some special name or marked with some attribute).

(As a side-note, using quotations or writing your own interpreter as mentioned in the related SO question may be an option if your source code is relatively simple, but probably not if you want to support the full power of F#)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文