I have been interested in F# for a long time, but haven't taken the time to actually do anything with it. Finally I decided to try and use it to implement the good old FizzBuzz. I used fsUnit as a unit test framework.
Here are the tests I ended up with:
[<TestFixture>]
type ``When to Fizz`` ()=
    [<TestCaseAttribute 1>]
    [<TestCaseAttribute 2>]
    [<TestCaseAttribute 4>]
    [<TestCaseAttribute 7>]
    member test.``numbers not divisible by 3 or 5 print themselves``(number) = 
        FizzBuzz number |> should equal (number.ToString()) 
    [<TestCaseAttribute 3>]
    [<TestCaseAttribute 6>]
    [<TestCaseAttribute 9>]
    [<TestCaseAttribute 12>]  
    member test.``multiples of 3 should fizz``(x) = 
        FizzBuzz x |> should equal "fizz"
    [<TestCaseAttribute 5>]
    [<TestCaseAttribute 10>]
    [<TestCaseAttribute 20>]  
    member test.``multiples of 5 should buzz``(x) = 
        FizzBuzz x |> should equal "buzz"
    [<TestCaseAttribute 15>]
    [<TestCaseAttribute 30>]
    member test.``multiples of 3 and 5 should fizzbuzz``(x) = 
        FizzBuzz x |> should equal "fizzbuzz"
The attribute-syntax is a bit of an eyesore to me, but it's just personal preference. The ``..``-syntax is quite cool when writing tests because ``multiples of 3 should fizz`` seems nicer that multiples_of_3_should_fizz.
Here is the FizzBuzz-function I ended up with:
type System.Int32 with 
    member x.is_multiply_of number = x % number = 0
let FizzBuzz (x:int) = 
    if x.is_multiply_of 3 && x.is_multiply_of 5 then "fizzbuzz"
    elif x.is_multiply_of 3 then "fizz"
    elif x.is_multiply_of 5 then "buzz"
    else x.ToString()
Very simple and pretty much what you'd expect. is_mutiply_of -function is a extension method to .NET Int32-class. if-else-construction is ok in this case, but not particularly elegant.
Couple of days later I ran into Phil Trelfords blog post which shows way use pattern matching instead of if-else-statements:
let FizzBuzz (x:int) = 
    match x.is_multiple_of 3, x.is_multiple_of 5 with
    true, true -> "fizzbuzz"
    |true, _ -> "fizz"
    |_, true -> "buzz"
    |_, _ -> string x
Software professional with a passion for quality. Likes TDD and working in agile teams. Has worked with wide-range of technologies, backend and frontend, from C++ to Javascript. Currently very interested in functional programming.
