Created
May 7, 2014 03:22
-
-
Save wangzaixiang/c1421fd18267812e83d0 to your computer and use it in GitHub Desktop.
FizzBuzzWhizz https://www.jinshuju.net/f/EGQL3D
This file contains hidden or 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
package fbw | |
object FizzBuzzWhizz { | |
implicit class RichBoolean(bool: Boolean) { | |
def option[T](value:T) = if(bool) Some(value) else None | |
} | |
implicit class RichOption[T](option:Option[T]) { | |
def elseFlatMap(value: =>Option[T]) = option match { | |
case Some(_) => option | |
case None => value | |
} | |
def elseMap(value: T) = option match { | |
case Some(_) => option | |
case None => Some(value) | |
} | |
} | |
def main(args: Array[String]) { | |
val (a,b,c) = (3,5,7) | |
(1 to 100).map { i => | |
(i.toString contains a.toString) | |
.option("Fizz") | |
.elseMap { | |
List( (i % a == 0).option("Fizz"), | |
(i % b == 0).option("Buzz"), | |
(i % c == 0).option("Whizz") ).flatten.mkString | |
} | |
.flatMap(x => if(x=="") None else Some(x)) | |
.elseMap(i.toString) | |
}.flatten.foreach(println) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment