Created
February 24, 2015 02:52
-
-
Save kamiyaowl/029d4c54ed2cd3699daf to your computer and use it in GitHub Desktop.
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
/** | |
* Created by kamiya on 2015/02/24. | |
* libraryDependencies += "org.scala-lang" % "scala-compiler" % scalaVersion.value | |
*/ | |
import scala.reflect.runtime.currentMirror | |
import scala.tools.reflect.ToolBox | |
object FizzBuzz { | |
class TraitCreator(name:String,const:String,superClass:String = "AnyRef") { | |
def make(n:Int = 1) : Stream[String] = | |
s"trait $name$n extends $superClass { $const }" #:: make(n + 1) | |
def get(n:Int = 1) : Stream[String] = s"$name$n" #:: get(n + 1) | |
} | |
class MemorizeTraitCreator(name:String,const:String,superClass:String = "AnyRef") extends TraitCreator(name,const,superClass) { | |
var currentN = 1 | |
def get : String = { | |
val g = super.get(currentN).head | |
currentN += 1 | |
g | |
} | |
def make : String = { | |
super.make(1).take(currentN - 1).mkString("",";",";") | |
} | |
} | |
def main(args:Array[String]) : Unit = { | |
val n = new MemorizeTraitCreator("N","println(n) ; incr","FizzBuzz") | |
val f =new MemorizeTraitCreator("F","println(\"Fizz\") ; incr","FizzBuzz") | |
val b = new MemorizeTraitCreator("B","println(\"Buzz\") ; incr","FizzBuzz") | |
val fb = new MemorizeTraitCreator("FB","println(\"FizzBuzz\") ; incr","FizzBuzz") | |
def fbgen(i:Int) = i % 15 match { | |
case 0 => fb.get | |
case x if x % 5 == 0 => b.get | |
case x if x % 3 == 0 => f.get | |
case _ => n.get | |
} | |
val g = "new Hoge(1)" + (1 to 100).flatMap(i => " with " + fbgen(i)).mkString | |
val d = "trait FizzBuzz extends AnyRef { var n:Int; def incr = n +=1 } ; class Hoge(var n:Int = 1) {} ; " + n.make + f.make + b.make + fb.make | |
val tb = currentMirror.mkToolBox() | |
println(tb.eval(tb.parse(d + g))) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment