Last active
December 12, 2015 00:18
-
-
Save sebnozzi/4682549 to your computer and use it in GitHub Desktop.
This is my "boring", "conservative", verbose, "my momma should grasp it" version of FizzBuzz...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object FizzBuzz extends App { | |
implicit class MyInt(thisNumber: Int) { | |
def isDivisibleByOrHasDigit(other: Int) = { isDivisibleBy(other) || hasDigit(other) } | |
def isDivisibleBy(other: Int) = (thisNumber % other == 0) | |
def hasDigit(c: Char): Boolean = thisNumber.toString.contains(c) | |
def hasDigit(x: Int): Boolean = { | |
assert(x >= 0 && x < 10, s"Number should be 1 digit long (found: $x)") | |
hasDigit(x.toString.head) | |
} | |
} | |
implicit class MySeq[T](seq: Seq[T]) { | |
def ifNotEmpty[R](block: Seq[T] => R)(ifEmpty: R): R = | |
if (!seq.isEmpty) | |
block(seq) | |
else | |
ifEmpty | |
} | |
case class SpecialWord(word: String, when: (Int) => Boolean) { | |
def correspondsTo(number: Int): Boolean = when(number) | |
override def toString = word | |
} | |
lazy val specialWords = Seq( | |
new SpecialWord("Fizz", when = { _.isDivisibleByOrHasDigit(3) }), | |
new SpecialWord("Buzz", when = { _.isDivisibleByOrHasDigit(5) }), | |
new SpecialWord("Wizz", when = { _.isDivisibleByOrHasDigit(7) })) | |
def specialWordsFor(number: Int): Seq[SpecialWord] = { | |
assert(specialWords != null) | |
specialWords.filter { _.correspondsTo(number) } | |
} | |
def fizzBuzzOf(number: Int): String = { | |
specialWordsFor(number).ifNotEmpty(_.mkString(" "))(ifEmpty = number.toString) | |
} | |
def fizzBuzzUpTo(upperBound: Int) = { | |
(1 to upperBound).toList map (fizzBuzzOf(_)) | |
} | |
} |
Note that ifNotEmpty/ifEmpty is a Smalltalk idiom. It looks much nicer in that language ;-)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think I got a Scala bug. If
specialWords
is not a lazy val, then I get a NPE when accessing it.It might be because I am importing the contents of the object (doing
import FizzBuzz._
) and then usingspecialWordsFor
. Then the Scala "runtime" does not see the need to initialize theval
?