【发布时间】:2012-03-30 14:54:37
【问题描述】:
如何获取应该是 F#-code 的文本字符串,并将其解析为 F#-code,以在屏幕上打印结果?
我猜它会通过 .NET 中的一个特性来解决,所以它可以通过 F# 本身或 C# 来完成。
tryfsharp.org 上可能通过什么方式解决?
【问题讨论】:
-
这可能值得一看question
-
你也可以使用f# codedom
如何获取应该是 F#-code 的文本字符串,并将其解析为 F#-code,以在屏幕上打印结果?
我猜它会通过 .NET 中的一个特性来解决,所以它可以通过 F# 本身或 C# 来完成。
tryfsharp.org 上可能通过什么方式解决?
【问题讨论】:
可以使用F# CodeDom provider 实现期望。下面的最小可运行 sn-p 演示了所需的步骤。它从字符串中获取任意可能正确的 F# 代码,并尝试将其编译为程序集文件。如果成功,它会从dll 文件加载这个刚刚合成的程序集,并从那里调用一个已知函数,否则它会显示编译代码的问题。
open System
open System.CodeDom.Compiler
open Microsoft.FSharp.Compiler.CodeDom
// Our (very simple) code string consisting of just one function: unit -> string
let codeString =
"module Synthetic.Code\n let syntheticFunction() = \"I've been compiled on the fly!\""
// Assembly path to keep compiled code
let synthAssemblyPath = "synthetic.dll"
let CompileFSharpCode(codeString, synthAssemblyPath) =
use provider = new FSharpCodeProvider()
let options = CompilerParameters([||], synthAssemblyPath)
let result = provider.CompileAssemblyFromSource( options, [|codeString|] )
// If we missed anything, let compiler show us what's the problem
if result.Errors.Count <> 0 then
for i = 0 to result.Errors.Count - 1 do
printfn "%A" (result.Errors.Item(i).ErrorText)
result.Errors.Count = 0
if CompileFSharpCode(codeString, synthAssemblyPath) then
let synthAssembly = Reflection.Assembly.LoadFrom(synthAssemblyPath)
let synthMethod = synthAssembly.GetType("Synthetic.Code").GetMethod("syntheticFunction")
printfn "Success: %A" (synthMethod.Invoke(null, null))
else
failwith "Compilation failed"
被点燃会产生预期的输出
Success: "I've been compiled on the fly!"
如果您要使用 sn-p,则需要引用 FSharp.Compiler.dll 和 FSharp.Compiler.CodeDom.dll。享受吧!
【讨论】:
我猜它会通过 .NET 中的一个特性来解决,所以它可以通过 F# 本身或 C# 来完成。
不。 F# 提供了相对温和的元编程工具。您需要从 F# 编译器本身中提取相关代码。
【讨论】:
F# 有一个解释器 fsi.exe 可以做你想做的事。我认为它也有一些 API。
【讨论】: