FizzBuzz using Scala StreamSunday, 27 Sep 2015, 12:20

By Simon

While I’m trying to wrap my head around the Stream class in scala, I’ve written this piece of code to implement FizzBuzz in an unusual way. (Sorry the first line is a bit long)

I think it’s an good example how the Stream class works and simpler to understand than the countless fibunacci examples

var fb:Stream[(Int, String)] = (1, "")#::(2, "")#::(3, "Fizz")#::(4, "")#::(5, "Buzz")#::(6,"Fizz")#::(7,"")#::(8,"")#::(9,"Fizz")#::(10,"Buzz")#::(11,"")#::(12,"Fizz")#::(13,"")#::(14,"")#::(15,"Fizzbuzz")#::fb.map{ case (x, y) => (15+x, y)};

fb take 100 foreach {case (a,"") => println (a); case (a, b) => println (b)}

So you may ask: ‘What the hell happens there?’.

It’s actually quite simple. The Stream object fb is basically an infinite List of tupel object’s. As soon as you’re trying to evaluate the element at index 15 you invoke map on the same list. Map is lazy and isn’t evaluated until a value is actually requested. Basically while you’re walking through the list from index 0 to infinity, you add 15 to the current element and attach the result at the end. So for the element (1, “”) map calculates (16, “”) at (15, “FizzBuzz”) => (30, “FizzBuzz”)

Leave a comment

Maximum of 50 characters.
Max 100 characters.
Required. Max 500 characters. Markdown is supported, but no images. Every Post will be checked befor it is shown