Sunday, December 9, 2012

FizzBuzz using a mapping

In functional programming one of the most used "tools" is the mapper.  The mapper is typical used to apply a function to elements of a list.



Using the image above we can imagine that we have a mapper which takes elements and changes the color to magenta, thus the blue circle A would be mapped to a magenta circle A, B to B, and C to C.  

Note that only the color has been changed.

If we want to do FizzBuzz in F# using a mapper we could do the following (using fsi.exe running against Mono).

> let x = [ 1 .. 31 ];;

val x : int list =
  [1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15; 16; 17; 18; 19; 20; 21;
   22; 23; 24; 25; 26; 27; 28; 29; 30; 31]

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

val fizzBuzzer : int -> string

> x |> List.map fizzBuzzer;;
val it : string list =
  ["1"; "2"; "Fizz"; "4"; "Buzz"; "Fizz"; "7"; "8"; "Fizz"; "Buzz"; "11";
   "Fizz"; "13"; "14"; "FizzBuzz"; "16"; "17"; "Fizz"; "19"; "Buzz"; "Fizz";
   "22"; "23"; "Fizz"; "Buzz"; "26"; "Fizz"; "28"; "29"; "FizzBuzz"; "31"]

In the code above, our list of numbers is x which holds the numbers 1 through 31.  We also have a function called fizzBuzzer which takes an int and outputs a string based on the typical FizzBuzz rules.  Last we use List.map to do a mapping of fizzBuzzer against x giving us a list of strings with the FizzBuzz rules applied.

Note, we could have done this very easily in one line of F#.