F# as a scripting language

rhemsta0

Vin Yu

Posted on September 22, 2024

F# as a scripting language

If you read on https://learn.microsoft.com/en-us/dotnet/fsharp/tools/fsharp-interactive/, F# language has an official interactive/interpreter support from Microsoft unlike C#. Let me know if I'm wrong guys please comment.

This means you could use F# in places where you are using interpreted/scripting language like Python, Perl, Ruby

Advantage you get to consume libraries from .NET ecosystem and strong type system of F#

At this time of writing, I'm using dotnet sdk 8.0

Step 1: Install paket

dotnet tool install -g paket
paket init
Enter fullscreen mode Exit fullscreen mode

Edit "paket.dependencies" and add your libraries you need.
For this example, I want to add "FSharp.Core" version "8.0.300" and "UUIDNext" version "3.0.0"

sources https://api.nuget.org/v3/index.json
storage: none

nuget FSharp.Core 8.0.300
Enter fullscreen mode Exit fullscreen mode

Step 2: Use "paket install" to install dependencies then "paket generate load-scripts --framework net8.0" to generate script to use to reference your dependencies in the script you will create

paket install
paket generate load-scripts --framework net8.0
Enter fullscreen mode Exit fullscreen mode

From one of the answers in stackoverflow, With the most recent cross plaform net installed and the most recent linux (coreutil 8.30<=) and bsd / mac os releases. You can use the following shebang for F# .fsx scripts.

#!/usr/bin/env -S dotnet fsi
Enter fullscreen mode Exit fullscreen mode

Here is a sample F# fsx script I will create named "uuid.fsx"

#!/usr/bin/env -S dotnet fsi
#load @".paket/load/net8.0/main.group.fsx"


open System
open UUIDNext

let sequentialUuid = Uuid.NewDatabaseFriendly(Database.SQLite)
Console.WriteLine($"This is a database friendly UUID : {sequentialUuid}")
Enter fullscreen mode Exit fullscreen mode

We can run this script from bash like we do with other scripts

./uuid.fsx
Enter fullscreen mode Exit fullscreen mode

or directly using dotnet command

dotnet fsi uuid.fsx
Enter fullscreen mode Exit fullscreen mode

Output:

This is a database friendly UUID : 0191ea67-c7bf-77e6-af05-483dea4b1c62
Enter fullscreen mode Exit fullscreen mode

Nice!. we are done

Reference: http://www.970101.xyz/2024/09/f-as-scripting-language.html

💖 💪 🙅 🚩
rhemsta0
Vin Yu

Posted on September 22, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related