Hands-on Introduction for Getting Started with F# in the Browser using tryfsharp.org
Guest blog by Jin Yun Soo Microsoft Student Partner at Imperial College
Hello, I am Jin. EnJineering is my tonic. I study Electrical and Electronic Engineering at Imperial College London, and have been involved in tech education and outreach through teaching children and teens coding. I am also a student champion/volunteer at the Imperial College Advanced Hackspace.
You can connect with me via LinkedIn and find out more about me from my personal website. I designed and coded my website using Angular, and then deployed it as a cloud app using Microsoft Azure App Service with the free Microsoft Imagine subscription (yay!) that they offer for students. I set up a Continuous Integration (CI) pipeline such that pushing changes to GitHub will trigger the build process on VSTS and update the Azure App automatically.
But of course, this blog is not about my story. It is about YOUR journey with technology. And in this article, I shall share with you how you can get started with the .NET functional programming language, F#, using tryfsharp.org.
Based on my personal experience and what I hear from my friends, students in engineering courses are not usually exposed to functional programming in the core curriculum, whereas students in computer science are typically introduced to different types of programming languages including functional in their first year. I find it rather odd because computation in functional programming works like an evaluation of mathematical functions, which should make it very intuitive for students in mathematics and engineering.
One of the key features that I like about functional programming is immutability. After being created, the state of an object cannot be modified. We need not worry about side effects. This gives us a peace of mind when working on multi-threaded applications. Particularly, F# is a typed language that is designed to be functional and includes .NET features such as runtime support, object model, and libraries. You can use F# with, for instance, Parallel Extensions for .NET. Parallel and asynchronous I/O programming can be made easier with F# asynchronous workflows. F# for Fun and Profit and Phillip Carter and Mads Torgersen from Microsoft's .NET team explained why you should use F# better than I could.
In this article, we will explore how we can use tryfsharp.org to, well, try F#. This platform offers a quick, easy, and effective way to learn and code F# using the browser. The tutorials are well structured and do not appear to be convoluted nor overwhelming. If you go to the Scientific and Numerical Computing section, you will be amazed by how complex logic for things that we are familiar with such as statistics, linear algebra, differential equations, and Fast Fourier Transform can be written so simply and elegantly in F#.
Figure 1: Six categories of tutorials in the Learn section of tryfsharp.org.
I asked a couple of friends to visit the site without giving them any heads-up so that I can understand what issues people who are just getting started might face. If you are using Chrome, the warning in the Output Window will not ask you to install the needed components because Chrome is not supported anymore. If you are using Firefox, you will be prompted with the link to install the plugin but you will not be able to enable the plugin in the latest Firefox.
Figure 2: Two possible warnings.
In short, it is probably safest to use Internet Explorer and install the Microsoft Silverlight plugin. If the problem persists, make sure the plugin is enabled for the tryfsharp.org website through your browser settings.
We shall use a very simple example, the recursive factorial function, to go through the core features of tryfsharp.org and pick up bits and pieces of the F# language syntax or style along the way.
1. Go here . On the left, you will see the Content Window which shows explanations and instructions for the tutorial. On the right, you will be able to type your code in the Script Window, and then see the results of running the code in the Output Window.
2. If you are
lazy to type, I mean, eager to go through it quickly, click ‘load and run’ to load the recursive factorial code to the Script Window, and run the code.
Note that if you click ‘load and run’ for, say, the recursive power function code below it now, the factorial code that is already present in the Script Window will be overwritten.
Figure 3: ‘Load and run’ code from tutorials in the Learn section.
Figure 4: When running the code without calling the function, the Output Window will show you that the function takes an input n of type integer and returns an integer.
According to the website, in cases where a code example has external dependencies, the code and references are loaded automatically with the example code. This feature is intended to allow each individual example to run independently.
3. Instead of following along the other examples or navigating to the next page (which you can do on your own), let’s continue to work on the factorial function. You can call the function like this:
Figure 5: Calling the factorial function.
I am serious. No brackets. No semi-colons. So clean and simple.
4. Let’s check the code with different types of input. Type the following into the Script Window without running the code. Hovering on the red curly underlined argument of the first line in Figure 6 shows ‘The value or constructor 'ilovefood' is not defined’, the second one shows ‘This expression was expected to have type int but here has type string’, whereas the third one shows ‘This expression was expected to have type int but here has type float’.
Figure 6: You will be alerted before even running the code. Neat.
Unlike languages like Python, when you use the wrong type in your F# code, you will be alerted before even running it . This makes debugging in F# easy.
5. Now, call ‘factorial’ using a negative integer like -10 as the input. The browser would show an error message and close. As you probably know already, this is because the base case of n=0 can never be reached, and thus causes a stack overflow exception.
6. We can continue to experiment and build on top of the given code. Use the ‘failwith’ function to raise an exception when n < 0. This makes the code more robust.
Figure 7: Use the ‘failwith’ function to raise an exception when n < 0.
7. Remember to use the keyword ‘rec’ when defining recursive functions. One advantage of the keyword ‘rec’ is reducing the probability of using recursion unintentionally.
8. Now, you may be thinking, ‘hmm, sounds good so far. But that is just a simple implementation of recursion. What about tail call optimisation?’ Let’s add the following chunk of code to the Script Window without removing the previous code:
Figure 8: Add tail recursive factorial function.
Note that in F#, ‘=’ instead of ‘==’ is used as a comparison operator to indicate equality.
9. If you keep experimenting like this, whether on the Learn or Create Interface, your code could become a lot longer and at some point, you might feel you only want to run and test out a certain part of the code. Typically, one would comment out and/or de-comment different parts of the code when one is experimenting with it. But this F# environment makes things even more convenient: if, say, you only want to run ‘factorialTail 10’, simply highlight that line and run it!
1. Copy the ‘factorialTail’ function in Figure 8 and proceed here. You can add and upload multiple files on the left, and then load them on the Script Window. This means you can download code samples from the web, and then upload them here to experiment with them. You can also save your code with the button above the Output Window. The rest is similar to the Learn Interface. I will, however, introduce a few new features here.
2. When using the features on the Create Interface, you will be prompted to get a nickname and sign in with your Microsoft or Facebook account.
3. Paste and save the ‘factorialTail’ function code. Let’s produce an array containing results for the factorials of 0 to 10 inclusive. For a typical imperative language, you would use a for loop or while loop. In F#, you can do it in one line, while being very clear about what the code is trying to do.
Figure 9: The map function applies the function ‘factorialTail’ to each element in the array of integers from 0 to 10 inclusive, and returns the array of results in the same order.
Figure 10: Resulting array displayed in the Output Window upon running the code.
Some other common and useful functions besides ‘map’ include ‘Reduce’, ‘Fold’, ‘Scan’, and ‘Filter’.
4. I find the following features very helpful when one is new to the functions available in F#.
Figure 11: When you type ‘.’ after ‘Array’, you will be prompted with a list of available functions that you can apply to it.
Figure 12: The Output Window will display information about the function as you scroll through the list of available functions.
5. Notice the ‘show canvas’ button on top of the Script Window? The canvas is where we can see plots and visualisations generated by our code.
Figure 13: One way to plot the graph for factorial.
Figure 14: Now we can visualise how bad algorithms of O(n!) complexity are!
6. Since this is a browser-based environment, we will not have full access to the .NET library. However, we can use all the F# language features including asynchronous and queries.
7. On the left window, click on your file to download or share it! You can view my file with this link
The Explore section provides some great information and resources! Now that you have had a glimpse of tryfsharp.org and F#, I hope you are excited to go through the tutorials as well as the resources.
‘But I am not sure if I want to do tech. I might venture into finance/consulting/business …’
If you are someone who thinks, ‘I am not confident in coding because it’s not intuitive to me’ or ‘I need to earn enough to pay off my student loans quickly, and I’m not sure I am good enough to be able to do so in the tech industry’, I recommend that you give F# a go. Many people I know find it intuitive due to its functional nature. You might surprise yourself.
Besides, functional programming has become very popular in various fields including science, data science, and financial computing.
Some thoughts about tryfsharp.org and my experience with functional programming
tryfsharp.org lowers the barrier of entry by providing useful tutorials and a browser-based environment that allows you to experiment with a lot of language syntax and features.
Based on my experience teaching kids coding and talking to people in my university, some people (including myself) have moments of doubt and thoughts like ‘I’m not good enough’ or ‘I started coding really late so I’m not sure I can do this right’. There might be this one guy in your school who wears a hoodie, has a lot of confidence in what he does, and started coding since the age of 7. But there are also lot of good techies who do not fit into the media stereotype. Besides, technology is evolving so quickly these days that it is a learning process every day even for the most experienced programmers.
I started off my internship at a financial technology company knowing nothing about functional programming. Yet I had to use a proprietary visual programming language (VPL) that is similar to F#. The projects assigned to me were experimental and rather different from what the team usually does, so there were no relevant past projects that I could refer to. Nevertheless, such circumstances allowed me to approach the problems with a fresh outlook. I discovered and documented some quirks of the VPL, and wrote sample use cases for some functions that were rarely used in their usual projects such that they can be applied in the context of the team’s work. By sheer hard work, I completed the internship with good reviews. My point is, newbies can still contribute in some ways, in different ways. Just keep thinking in terms of learning and growth.