Skip to main content

F# Interactive Example

F# Interactive (FSI) is a powerful tool for executing F# code snippets and scripts in an interactive environment. It allows you to quickly test and iterate on your F# code without needing to create a full project structure.

Using F# Interactive with ModularPipelines​

  1. Create a new F# script file: Create a new file named example.fsx (or any name with .fsx extension).

  2. Add ModularPipelines to your script: You can add ModularPipelines as a package reference in your F# script. At the top of your example.fsx, add the following line:

    #r "nuget: ModularPipelines, 4.*"

    Alternatively, you can specify a specific version:

    #r "nuget: ModularPipelines, 4.0.0"
  3. Write your F# code: Below the package reference, you can write your F# code using ModularPipelines. Here’s a simple example that uses ModularPipelines to update .NET workloads and check the installed SDKs:

    #r "nuget: ModularPipelines.DotNet, 4.*"
    open ModularPipelines.DotNet.Extensions
    open ModularPipelines.DotNet.Services
    open ModularPipelines.Extensions
    open ModularPipelines
    open System.Threading

    type UpdateDotnetWorkloads() =
    inherit Module<CommandResult>()
    override this.ExecuteAsync (context: IModuleContext, cancellationToken: CancellationToken): System.Threading.Tasks.Task<CommandResult> =
    context.Tools.Get<IDotNet>().Workload.UpdateAsync(cancellationToken = cancellationToken)

    /// Generic attributes are not supported in fsharp, so have to use the old way of declaring dependencies
    [<DependsOn(typeof<UpdateDotnetWorkloads>)>]
    type CheckDotnetSdkModule () =
    inherit Module<CommandResult>()
    override this.ExecuteAsync (context: IModuleContext, cancellationToken: CancellationToken): System.Threading.Tasks.Task<CommandResult> =
    context.Tools.Get<IDotNet>().Sdk.CheckAsync(cancellationToken = cancellationToken)

    let args = System.Environment.GetCommandLineArgs()
    let builder = Pipeline.CreateBuilder(args)
    builder.Services.RegisterDotNetContext() |> ignore

    builder
    .AddModule<UpdateDotnetWorkloads>()
    .AddModule<CheckDotnetSdkModule>()
    |> ignore

    builder.RunAsync()
    |> Async.AwaitTask
    |> Async.RunSynchronously
    |> ignore
  4. Run your F# script: You can run your F# script using the F# Interactive environment. If you are using Visual Studio, you can simply open the example.fsx file and execute it. Alternatively, you can run it from the command line using:

    dotnet fsi example.fsx

Additional Notes​

  • Fsharp Interactive does allow you to have modules and types across different files, for simplicity we have only 1 file in this example.
  • The fsharp compiler does not support generic attributes
  • The fsharp compiler requires code and files to be declared in order, due to the fsharp compiler being sequential. For example, if you have a module that depends on another module, the module it depends on must be declared first.