DEV Community

Assis Zang
Assis Zang

Posted on

Creating an easy algorithm in F#๐ŸฆŠ

I've been programming in C# for the last 8 years, but now I decided to learn a new functional programming language and my choice was F#.

One of the best ways to learn a new programming language is to practice algorithms in the new language.

So today let's create an easy algorithm in F#. This algorithm is very common in programming challenges websites like Hackerrank, Leetcode, and others...

The algorithm consists of the sum of all elements in an array and then prints the result. As I said, this is very easy.

So, to create the sample application in F# you must install the last .NET SDK.

This tutorial will use the Visual Studio Code and the extension Ionide for F#.

Then, write the following code in the terminal:

dotnet new console -lang "F#" -o ArraySumPractice
Enter fullscreen mode Exit fullscreen mode

So, open the folder with your favorite IDE, I recommend the Visual Studio Code.

In the Program.fs file add the code below:

let arr = [|1; 2; 3; 4; 10; 11|]
let totalsum = Array.sum arr

printf "The total sum is %d\n" totalsum
Enter fullscreen mode Exit fullscreen mode

Here we declared a variable called arr that receives an array with some integer values, and then we declared another variable called totalsum that receives the sum of all the values in the array. Finally, the total value is printed in the console.

To execute this code, select all code, and then in Windows hold the Alt key and hit Enter and in macOS hold the Option key and hit Enter this command will open a terminal window pop up on the bottom of the screen, and it should look similar to this:

Running the code in VS Code

Note that the phrase The total sum is 31 is displayed on the window, and now our algorithm is finished.

The same code in C# can be written as follows:

int[] arr = [1, 2, 3, 4, 10, 11];
int totalSum = arr.Sum();

Console.WriteLine($"The total sum is {totalSum}");
Enter fullscreen mode Exit fullscreen mode

Top comments (0)