1

The many faces of F#

by klh 30. september 2008 11:20

I have been looking at the many different ways you can do a thing in F#.

So as an instance I use Fibbonacci:

Here's the way a C# programmer would do it:

int Fibonacci(int n)
{
  if (n < 2)
    return n;
  else
    return Fibonacci(n - 1) + Fibonacci(n - 2);
}
 
Here's what to do with pattern matching (and recursion):
let rec fib n =
  match n with
  | 0 -> 0
  | 1 -> 1
  | _ -> fib(n - 1) + fib(n - 2)
 
Less readable but still pattern matching (and recursion):
let rec fib n =
    match n with
    | 0 | 1 -> n
    | _ -> fib (n - 1) + fib (n - 2)

Unreadable for a C# programmer, using lazy lists (from "Foundations of F#" which I won at last ANUG)
let fibs =
     Seq.unfold
       (fun (n0, n1)  ->
           Some(n0, (n1, n0 + n1)))
       (1I,1I)
 
let first20 = Seq.take 20 fibs
 
print_any first20

Powered by BlogEngine.NET 1.4.5.0
Original Design by Laptop Geek, Adapted by onesoft