Kata FizzBuzz in F#

Last F# book club meeting in Munich was awesome (as usual). 2 weeks ago we decided to do a Code Kata on each subsequent meeting. This week was our first, with Kata FizzBuzz.

This is what we came up with. (BTW: Partial function application and pipelining rocks !!!)


open Xunit  

let fizzBuzz number =
     match number with
     | n when n%15=0 -> "FizzBuzz"
     | n when n%3=0 -> "Fizz"
     | n when n%5=0 -> "Buzz"
     | _ -> number.ToString()  

let areEqual expected actual =
     Assert.Equal(expected, actual)  

[<Fact>]
let Should_return_the_digit_for_numbers_which_are_not_dividable_by_3_or_5()  =
    [1;2;11;13;16]
    |> List.map fizzBuzz
    |> List.iter2 areEqual ["1";"2";"11";"13";"16"]  

[<Fact>]
let Should_return_Fizz_for_digits_dividable_by_3() =
    [3;6;9;12]
    |> List.map fizzBuzz
    |> List.iter (areEqual "Fizz")

[<Fact>]
let Should_return_Buzz_for_digits_dividable_by_5() =
    [5;10;20;25]
    |> List.map fizzBuzz
    |> List.iter (areEqual "Buzz")  

[<Fact>]
let Should_return_FizzBuzz_for_digits_dividable_by_3_and_5() =
    [15;30;45;60]
    |> List.map fizzBuzz
    |> List.iter (areEqual "FizzBuzz")  

If anyone of you hardcore functional guys out there notices something utterly wrong or something that could radically simplified, please let me know. We’re eager to learn more.

Kick it on dotnet-kicks.de Kick it on DotNetKicks.com
BjRo posted at 2010-4-29 Category: F# | Tags:

6 Responses Leave a comment

  1. #1stringer @ 2010-5-3 15:07

    You can use double quotes for identifiers:

    let “Should return Fizz for digits dividable by 3“ () = …

    It’s what the F# team use in their test frameworks (according Brian McNamara). I’m using this syntax too now (more readable, more fast to type in).

  2. #2BjRo @ 2010-5-3 19:43

    Yes, this is probably a good idea. Reads way better. Thanks for mentioning.

  3. #3Ilker Cetinkaya @ 2010-5-4 12:39

    OMG, it’s such a shame I missed last book club meeting. You seem to progress way faster than me :/ I’m in snail’s pace admittedly. Hope I can join you next time! Although I literally know nothing about F#, one question immediately came to my mind after having read the code: Is there a “nicer” language construct for “List.iter”? I mean something like PoShy %{}? Nevertheless, code is smart!

  4. #4BjRo @ 2010-5-4 13:56

    Bring a kata with you next time and we’ll try to figure out a better way ;-)

  5. #5Mark Needham @ 2010-5-4 22:35

    You could also define the fizzBuzz function like this:

    let fizzBuzz = function | n when n%15=0 -> “FizzBuzz”
    | n when n%3=0 -> “Fizz”
    | n when n%5=0 -> “Buzz”
    | n -> n.ToString()

    Apart from that it looks cool.

    Cheers, Mark

  6. #6BjRo @ 2010-5-4 23:39

    Thanks Mark. Wasn’t aware of that syntax. I’m going to try that out for sure . . .

Leave a Reply

(Ctrl + Enter)