Month: March 2014

A functional Fizzbuzz

Posted on Updated on

After reading Scott Wlashin’s post (http://fsharpforfunandprofit.com/posts/railway-oriented-programming-carbonated/) on writing FizzBuzz in a more functional style and with the ability to have more rules (other than 3 => fizz, 5 => buzz, etc) I decided to give it a go myself. This represents the most idiomatic F# I could come up with, and I think it reads pretty well. It uses partial application, list operations, shorthand match-expressions-as-functions and option types.

let carbonate rules i =    
    rules
    |> List.choose (fun (divisor, replacement) ->
        if i % divisor = 0 then Some replacement else None)
    |> function [] -> string i | list -> String.concat "" list
        
let carbonateAll rules = List.map (carbonate rules)
    
let fizzbuzzbazz = carbonateAll [3, "fizz"; 5, "buzz"; 7, "bazz"]

fizzbuzzbazz [100..110] |> printfn "%A"

See if you can follow how it works.