Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FSharp embedded API add variables

Using the Fsharp.Compiler.Serice Interactive API I'd like to set variables to my FsiEvaluationSession object. Is this possible? Or is there another way to embed f# into an application for embedded-scripting purposes?

like image 250
RoyalPotato Avatar asked Apr 08 '16 20:04

RoyalPotato


1 Answers

I don't think there is a direct way to do this, but there is a lovely 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"

This uses the evalExpressionTyped helper from the FCS documentation.

like image 170
Tomas Petricek Avatar answered Nov 02 '22 21:11

Tomas Petricek