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" (List.map 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!