I'm currently learning functional programming with scala and as a practice I've implemented FizzBuzz. To be honest, I made three different implementations of FizzBuzz but only the third one is good.
Stream.from(1) # Create infinite lazy stream from 1
.map { (_, "") } # convert it to (number, word) tuple
.map { x => if (x._1 % 3 == 0) (x._1, x._2 + "Fizz") else x } # Add "Fizz" to each 3rd word
.map { x => if (x._1 % 5 == 0) (x._1, x._2 + "Buzz") else x } # Add "Buzz" to each 5th word
.map { x => if (x._2 != "") x._2 else x._1.toString } # Take word or number
.take(30) # Limit stream length
.foreach(println) # Run everything and print results
It's even much better than usual imperative implementation and here's why.