FSharp 嵌入式 API 添加变量

Roy*_*ato 5 f# f#-interactive f#-compiler-services

使用Fsharp.Compiler.Serice Interactive API我想为我的 FsiEvaluationSession 对象设置变量。这可能吗?或者是否有另一种方法可以将 f# 嵌入到应用程序中以用于嵌入脚本?

Tom*_*cek 4

我认为没有直接的方法可以做到这一点,但有一个可爱的解决方法:

// Define a mutable variable with default value
fsiSession.EvalInteraction "let mutable myVar = Unchecked.defaultof<int>"

// Create a function that sets the value of the variable
let f = evalExpressionTyped<int -> unit> "fun x -> myVar <- x"  

// Run the function to set the value of `myVar` to whatever we want
f 42

// As a bonus, use variable shadowing to make it immutable
fsiSession.EvalInteraction "let myVar = myVar"
Run Code Online (Sandbox Code Playgroud)

这使用evalExpressionTypedFCS 文档中的帮助程序。