The familiar for loop featured in most if not all impertive langagues is not part of most functional languages if any because it has the mutable loop index. The standard way of looping in F# is to use recursion.

In the solution to Project Euler problem 7 I have the following function

let rec findprime primes test = if isprime primes test then test else findprime primes (test+2)

Notice that the recursive call is placed as the very last operation in the function and it is therefore a tail call. Using the tool Reflector it is possible to obtain a C# version of the program:

public static int findprime(FSharpListprimes, int test) { while (!isprime(primes, test)) { test += 2; primes = primes; } return test; }

We see that the compiler has transformed the recursive function into a function without recursion.

You can use the comment system below or send my an email mic.jacobsen@gmail.com

comments powered by Disqus