Getting F(#)nctional

The # in its name makes F# a functional programming language that is part of the .NET family. Although, it is possibly one of the lesser-used and lesser-known language options available to .NET developers.

What this means is that you can start coding in F# using the free Community edition of the latest Visual Studio, or even using MonoDevelop (which supports Linux and OS X as well). Since it runs on .NET it can run wherever .NET can run.

Just like C++, C#, JavaScript etc. trace their syntax to C and its predecessors, F# can trace its roots in the ML programming language. In fact, you will find that all the code in this article will run in OCaml with minimal modification. OCaml is another language descended from ML, and might be of interest to you if you like F# but don’t want to get into .NET.

The F# language is vast, and it’s impossible to cover its entire syntax here. So instead we will focus on what makes it different.

Setting up F

Getting a hold of F# is quite easy, as they are clear instructions available on the F# website: http://fsharp.org/
On Windows you can install the latest version of Visual Studio Community edition and you will be able to create F# projects. It will automatically install the F# tools. Another option is to use MonoDevelop, which is available for Linux and OS X as well. Xamaran Studio, a commercial version of MonoDevelop is also available to OS X and Windows users. You can get the F# compilers and interpreters for your Linux distro as well if you just want CLI tools. If you have just the F# compiler installed, simply create a text file ending with ‘.fsx’ in your favourite editor, and type your code in that. This code can then be compiled with the F# compiler located at:

C:\Program Files (x86)\Microsoft SDKs\F#\4.0\
Framework\v4.0\fsc.exe
The interactive interpreter is available on Windows at:
C:\Program Files (x86)\Microsoft SDKs\F#\4.0\
Framework\v4.0\fsi.exe

On Linux and OS X these commands should be available as fshasrpc and fsharpi respectively. You should also be able to find F# plugins for the free Atom code
editor and Sublime Text.

What is a functional Language?

There can be entire books dedicated to elaborating what exactly is a functional language and how F# figures into all of it. Simply put, functions are central to a functional language, such like objects are in an object-oriented language.

minar

With minor changes (just remove capitals from variable names in some cases) you can have most of the code from this article running in OCaml.

intractive

F# Interactive is a great way to get started with F# code. Always remember to type ‘;;’ after a block of code to tell the interpreter to execute it.

Functions are first-class members of a functional language, meaning that they can be passed around to other functions, stored in variables, combined and operated on just like any other value. Functions can accept other functions as parameters (such functions are called higher order functions) and they are an important part of functional programming. Functional languages also favour immutability and functional purity.

What is Immutability

While in most object-oritented and imperative languages when you constantly change the values of variables to perform computations, functional languages go for a more mathematical route, once you define a value it can’t change. Let’s see this in action, by getting things wrong. Open the F# interactive console and type the following:

let x = 11;;

Note the double semicolon at the end of the line. You do not usually need this while coding in a text file, however while working in the interactive interpreter it is required to tell the F# interpreter where an expression ends. You can print the value of x at any time by simply typing x;; at this prompt. Now 11 is a rather dull number, let’s try to set x to something cool, like 42. In most languages this would be as simple as setting

x to 42 or adding 31 to it. Let’s try both:
x = 42;;
x = x + 31;;

In both cases you should see output like:

val it : bool = false

This is probably not what you were expecting. In F# the above two lines are actually checking if x is equal to 42 or if x is equal to x + 31, both are obviously false. This is equivalent to x == 42 or x == x + 31 in languages like Java, C++ etc.

In fact, since ‘variables’ don’t really vary in F# they are generally called identifiers, and by using them, you are said to be binding a value to an identifier. There are ways to change the value of a variable in F# using the syntax x <- 42 , however, even that will fail in this case since x is immutable by default. In fact try it right now and see F# complain. It is possible to declare x such that it can be modified but we won’t go into that here, that’s not what functional programming is about. But you are free to explore that on your own.

What are Pure Functions

Pure functions are another core principle of functional programming languages. While most functional programming languages allow for some ‘impure’ functions, they highly emphasise writing functions that are pure.
A pure function is one simply takes its parameters and produces a single output. It is not affected by anything outside the function, and it affects nothing outside the function.

This is similar to how mathematical functions work. You don’t expect the sine of a value to change when you calculate it multiple times, nor do you expect the value of the sine function to depend on the previous value of sine.

Pure functions don’t use or change global variables or the parameters they receive. Technically, multiple calls to a traditional printf function will produce output in different lines, thus it’s output is dependent on previous calls. Similarly date / time / random number generator functions are impure because they return a different output each time. So obviously its impossible to be completely pure without entirely crippling your software. If you’re wondering why it’s advantageous to put these restrictions on yourself, know that such a design makes it very easy to parallelise your applications and make them multi-threaded.

Functions

Since we are looking at a functional language, it’s only fair that we start by looking at functions. You’ll be pleased to know that creating a function is very simple:

let sum a b =
a + b

Indentation matters in F# just like in Python, although you could have written the above in a single line if you wanted. Remember that in the interpreter you need to type ;; after typing some code to evaluate it, simply pressing return isn’t enough.

xy

Functions in functional languages try to model mathematics. So while two different inputs can gave the same output (square of both -2 and 2 is 4), a single input should not have multiple possible outputs.

A core facet of functions in F# is currying, or partial application of functions. This allows you to provide the parameters to a function in parts rather in one go.

For instance, if a function needs four parameters, you can provide two of them, and rather than raise an error you will get back a function that can take the rest of the parameters. Imagine we have a function to calculate the simple interest based on the rate and time. There are many accounts but the rate remains the same. Rather than provide a rate each time, we can supply that once and use the result. Let’s see it in action:

let simple_interest rate time principal =
principal * time * rate / 100
let si_4pc = simple_interest 4
let account1 = si_4pc 3 1000
let account2 = si_4pc 2 3000

In the above code sample, we create this simple interest function and supply only one parameter. This returns a function that is the simple_interest function with a rate of 4 per cent applied. Then we can use this new function si_4pc to calculate the interest for different time periods and principal amounts.

Another brilliant thing about F# functions is how easy they are to combine. In most languages if you had to take a value and apply multiple operations to it in series you would do something like:

result = sum( range( square( double( x ) ) ) )

Now this can be a little confusing since the operators appear in the opposite order in which the data is flowing. First x is doubled, then squared and so on. In F#, the same is done in this manner:

let result = x |> double |>
square |> range |> sum

Here F# will pass x as a value to double, pass the result of that to square, the result of that to range and finally to sum. If you wanted to make a new function that combined these functions you could do that as simply as:

let doubleSquareRangeSum = double
>> square >> range >> sum

Leave a Comment

Your email address will not be published. Required fields are marked *