.net - 将文本字符串解析为 F# 代码

标签 .net parsing f#

如何将文本字符串(应该是 F# 代码)解析为 F# 代码,以在屏幕上打印结果?

我猜它会通过 .NET 中的一个特性来解决,所以它可以通过 F# 本身或 C# 来完成。

这在tryfsharp.org上可能以何种方式解决?

最佳答案

可以使用 F# CodeDom provider 实现所需的功能.下面的最小可运行代码段演示了所需的步骤。它从字符串中获取任意可能正确的 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!"

如果您要使用该代码段,则需要引用 FSharp.Compiler.dllFSharp.Compiler.CodeDom.dll .享受!

关于.net - 将文本字符串解析为 F# 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9945382/

相关文章:

c# - 在 C# 中,如何确定不同文化中的一周开始时间是星期一还是星期日

.net - 使用 MongoDb 处理迁移

json - 解析 JSON 并遍历 Scala 中的对象

php - 在 php 中从 Markdown 生成目录

string - 如何将 f64 转换为 String 并解析回 f64?

f# - f# 有没有办法对列表执行交叉操作?

c# - 偶尔错误: The type 'HttpRequestMessage' is defined in an assembly that is not referenced

csv - F# 中读取 csv 文件的库

memory - 了解 F# 内存消耗

javascript - 用 Breeze 加载元数据很慢