Add API variables in FSharp

Using the Fsharp.Compiler.Serice Interactive API I would like to set the variables in my FsiEvaluationSession object. Is it possible? Or is there another way to embed f # in an inline script application?

+4
source share
1 answer

I don't think there is a direct way to do this, but there is a great workaround:

// 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"

In this case, the evalExpressionTypedassistant from the FCS documentation is used.

+3
source

All Articles