F# – Flow Control

In continuing our look at F#, I’d like to look at flow control, like conditional and looping of logic.

Before I get to that, I mentioned in my previous post,  that F# uses a type inference, which means the compiler can guess which type the variables and methods are.  However, you can also explicitly declare a variable type.

For example, here is a function that takes in a string parameter, we are declaring the input as a string type.  You can see how the function is called and passed input parameters from the EntryPoint main method:

Now, I can add a little logic to this and determine if the name provided is an expected value, and return a different Hello.


Now, for loops I will start with the for .. to loop.  You can either do a “for..to” or a “for..downto”  loop which as you can guess either counts up, or counts down.  I also wanted to remind you what I said earlier, that the indention defines the scope.

For my first attempt at a loop you can see here:

which outputs:

which isn’t what we want, to fix we need to un-indent the second printfn statement, which will remove it from that for..downto logic.

Which will output the expected logic:


Now, for the final loop I’m going to cover today is a “while..do” loop.  This works as you expect, but to do a play on the “fizzbuzz” programming test

There are some important concepts that we need to go over to get this to work.  First is the “mutable” keyword.  F# requires you to declare your variables mutable so it knows that you plan on changing its value.  Its as if, thinking in c# terms, each declared variable is readonly by default, and you have to “unreadonly” the variable.  It is different, and I can see the benefit. Then, after you declare a variable mutable, then when you want to update the value, you need to use the “<-” operator to assign a value to a variable.  This is also easily recognizable.

This example will loop, until a “FizzBuzz” is found, which is a number divisible by 3 and 5.  Then it will print “FizzBuzz” and exit the loop.


Hope that shows you how to start thinking in F# and control that flow.  Next week, I will go over arrays.

Leave a Reply

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