Thursday, May 22, 2008

FizzBuzz with F#

Once again, I'm going to give a solution to the fizz buzz problem, but this time in a, for me, completely new language - F#!

I've been following the articles on Why I Love F# by Dustin Campell, but even though I was inspired by the language, I never got to download F# and try it... until this very day! I installed it an hour ago, experimented some, and just have to share my experience. As a first mission I tried to write a solution for the fizz buzz problem, and (with some basic knowledge from haskell programming) it didn't take me too long to find a solution. Here it is:

let fizzBuzz (x:int) =
match x with
| x when x % 15 = 0 -> "FizzBuzz"
| x when x % 3 = 0 -> "Fizz"
| x when x % 5 = 0 -> "Buzz"
| x -> x.ToString()

let main = System.Console.WriteLine(String.concat "\n" ( fizzBuzz [1..100]))

More or less the same solution as the one given by bugrit in the last post. The fizzBuzz function takes an integer and returns the fizzbuzz string representation of that number, using pattern matching. Unfortunate, you have to specify the type of the argument because F# can't infer the type when using x.ToString() (because ToString() is a member function of object, which can be of any type).

The main function uses String.concat to concatenate the strings returned by fizzBuzz. In F#, all basic functions are put in libraries, which as prefixed with their name, such as String and List. They resemble namespaces in C# a lot, and by using the open keyword you can use all functions in a given library globally, without the prefix.

There are a lots of more stuff to find out about the language, for example how to integrate it with your current C# project. I'll blog about it if I have time to try it out!


peter h said...

Real nice! Maybe F# will sneak into some biopix code in the future :-)

Christian Genne said...

Haha, that would be wonderful :)

johno said...

yeah, but what are you guys developing with all this? it all seems very academic to me, but maybe that's the point :)

Christian Genne said...

Well, I don't know for sure, but if you can integrate it with your C# code, it might be possible to move most of your logics to F#, while still using C# for the GUIs. Because F# has the same support for .Net as C# does, everything you can do in C# you can do in F#, but (often) in less code. I'll give you a better example if I get the time to test it further. Perhaps Peter can try to use it in his application? :)