I have in my life programmed in a lot of languages like Java, C, Assembler, Python, Object C, PHP, but I was first introduced to F# (F Sharp) when I began studying Computer Science at the Copenhagen University.
So the functional style is much closer to a mathematical function. Lets look at a simple mathematical function:
There are no posibilities to change anything once you have assigned a value to x. For instance you can set and get the folowing calculation:
You plug in a number for and get an answer back. This is a function. No more, no less. Lets see that in F#:
let f x = x + 5
In programming we need some way to make different choices. In other language we use an ‘if’ statement, but not in a functional language. First we see how it works in math:
If we let we get . If we let we get . This is a conditional function. If is zero just return 0, but otherwise add 2. This is in F# done with pattern matching. Please note that the cases are evaluated in order so the first match will execute its statement after ‘->’ and skip the rest. So if the line 3 is executed and nothing else, and otherwise is matched by the 3rd line and is executed. But lets take a look:
let f = function | 0 -> 0 | x -> x+2
The left side of ‘->’ is the pattern we are looking for. The right size is what we return.
Functional languages do not use for or while loops. “How is it even possible to do anything that other languages can do?”, you might ask. We look at math again! Lets assume that we want to make a function that takes an input and we want to get the result .
First of all we see that . We also observe that . But then
We put this in a conditional mathematical function:
We now have a mathematical function that uses itself. You can say the function bites its own tail. Lets see what happens if we set and calculate .
First we get
And then we calcuate .
And last we get . We then go backwards
This is done in F# as follows
let rec f = function | 1 -> 1 | n -> (f (n-1)) + n
When a function is calling itself it is called a recursive call. Recursion is used instead of for and while loop in a functional language. If we would have made this in Java or other non-functional languages we could have used a for loop, but we needed to keep track of the loop with an iterator i and a variable that would accumulate the sum. Hence the functional approach is much shorter and elegant.
Now continue to part 2 of this small introduction: Part 2