Wednesday, July 29, 2009

Fibonacci Sequence, I totally know you

Edit -> sorry about the formatting, it exploded and I am far to lazy to fix it.

So I have looked at the first tutorial of F# and created my first program which I will get onto in a minute.

My first impressions is that F# is the bastard son of many programming ideas, for example each of these are valid forms of iteration within F#

let processItems (items : Item []) = 
  for i in 0 .. items.Length do
    let item = items.[i] in
      proc item

And

let rec processItems = function
  | []       -> ()
  | hd :: tl ->
      proc hd;
      processItems tl // recursively enumerate list

And

for item in collection do 
  process item

So to say it is a functional langauge isn't entirely correct. It is a mixed paradigm
taking ideas from OO, imperative and functional, which in itself is really 
interesting. 

Onto my sample program, like most tutorials the first thing they get you to do is a 
fibonacci sequence generator.

Here she is

start code

#light open System  let rec fib = function
    | 0 -> 0
    | 1 -> 1
    | n -> fib (n-1) + fib (n-2) 
let main() = 
    Console.WriteLine("fib 1 = {0}", (fib 1))
    Console.WriteLine("fib 2 = {0}", (fib 2))
    Console.WriteLine("fib 3 = {0}", (fib 3)) 
    Console.WriteLine("fib 4 = {0}", (fib 4))
    Console.WriteLine("fib 5 = {0}", (fib 5)) 
main()

end code


The #Light line is a nice one, when playing in the REPL everything was of this sort 
of format

let x = 5;;

But #light allows the programmer to omit redundant tokens such as the ';;' and it 
makes whitespace important. So so tabs throw warnings, but if you have set up your 
vim correctly, it will have no issue.

Secondly pattern matching. You do not need to use if, else, switch etc statements 
which is cool. From my understanding of erlang, F# seems to offer a nice stepping in 
point to a very unique language. But that being said I do not know enough about either
language to support that claim very well.


No comments:

Post a Comment